Esempio n. 1
0
VOID AddToLog(WCHAR *txt, PUNICODE_STRING txt1, ULONG *StatusCode)
{
 IO_STATUS_BLOCK		LogFileStatusBlock;
 HANDLE					LogFileHandle = 0;
 NTSTATUS				ns;
 // Проверка, разрешено ли протоколирование
 if (!EnableLog) return;
 __try {
 // Подготовка атрибутов файла
 OBJECT_ATTRIBUTES   	ob;
 InitializeObjectAttributes(&ob,
	 &usLogFile,
	 OBJ_CASE_INSENSITIVE + OBJ_KERNEL_HANDLE,
	 NULL, NULL);
 // Создание/открытие файла
 ns = ZwCreateFile(&LogFileHandle,
	               FILE_APPEND_DATA + SYNCHRONIZE,
				   &ob,
				   &LogFileStatusBlock,
				   0, FILE_ATTRIBUTE_NORMAL, 0, 
				   FILE_CREATE + FILE_OPEN, 
				   FILE_SYNCHRONOUS_IO_NONALERT, 
				   NULL, 0);
 if (ns == STATUS_SUCCESS) 
 {
	 // Буфер строки
	 WCHAR			Buffer[1024], CodeTxt[20];
	 ULONG          BuffSize = 0;
	 // Очистка буфера строки
	 RtlZeroMemory(&Buffer, sizeof(Buffer));
	 // Копирование строки
	 wcscpy(Buffer, txt);
	 // Добавление второй необязательной строки
	 if (txt1 != NULL && txt1->Buffer != NULL) {
		 __try {
			 for (int i = 0; i < txt1->Length / 2; i++)
				 if (txt1->Buffer[i] == 0)
					 txt1->Buffer[i] = L'*';
		 } __except(EXCEPTION_EXECUTE_HANDLER) {}
		 wcscat(Buffer, (wchar_t *)txt1->Buffer);
	 }
	 // Добавление парметра
	 if (StatusCode != NULL) {
		 if (*StatusCode == 0)
			 wcscat(Buffer, L" - succeeded");
		 else {
			 wcscat(Buffer, L" - failed (0x");
			 swprintf(CodeTxt, L"%X", *StatusCode);
			 wcscat(Buffer, (wchar_t *)CodeTxt);
			 wcscat(Buffer, L")");
		 }
	 }
	 // Добавление к нему CRLF	
	 wcscat(Buffer, L"\r\n");
     BuffSize = wcslen(Buffer) * 2;

	 zDbgPrint("%S", Buffer);
	 if (AnsiLog) {
		 // Преобразование буфера в ANSI
		 ANSI_STRING		AnsiString;
		 UNICODE_STRING     UnicodeString;
		 RtlInitUnicodeString(&UnicodeString, Buffer);
		 if (RtlUnicodeStringToAnsiString(&AnsiString, &UnicodeString, TRUE) == STATUS_SUCCESS)	  
			 // Запись AnsiString 
			 ns = ZwWriteFile(LogFileHandle, 0,
						NULL,NULL,
						&LogFileStatusBlock,
						AnsiString.Buffer,
						AnsiString.Length,
						NULL,NULL);
	 }
	 else 
		 // Запись буфера c UNICODE строкой
		 ns = ZwWriteFile(LogFileHandle, 0, 
		 NULL,NULL,
		 &LogFileStatusBlock,
		 Buffer,
		 BuffSize,
		 NULL,NULL);
	 ZwClose(LogFileHandle);
 }
Esempio n. 2
0
int removeNetworkInterface(MSIHANDLE hModule, const WCHAR *pwszGUID)
{
    int rc = 1;
    do
    {
        WCHAR wszPnPInstanceId[512] = {0};

        /* We have to find the device instance ID through a registry search */

        HKEY hkeyNetwork = 0;
        HKEY hkeyConnection = 0;

        do /* break-loop */
        {
            WCHAR wszRegLocation[256];
            swprintf(wszRegLocation,
                     L"SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\%s",
                     pwszGUID);
            LONG lStatus = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRegLocation, 0, KEY_READ, &hkeyNetwork);
            if ((lStatus != ERROR_SUCCESS) || !hkeyNetwork)
                SetErrBreak((L"VBox HostInterfaces: Host interface network was not found in registry (%s)! [1]", wszRegLocation));

            lStatus = RegOpenKeyExW(hkeyNetwork, L"Connection", 0, KEY_READ, &hkeyConnection);
            if ((lStatus != ERROR_SUCCESS) || !hkeyConnection)
                SetErrBreak((L"VBox HostInterfaces: Host interface network was not found in registry (%s)! [2]", wszRegLocation));

            DWORD len = sizeof(wszPnPInstanceId);
            DWORD dwKeyType;
            lStatus = RegQueryValueExW(hkeyConnection, L"PnPInstanceID", NULL,
                                       &dwKeyType, (LPBYTE)&wszPnPInstanceId[0], &len);
            if ((lStatus != ERROR_SUCCESS) || (dwKeyType != REG_SZ))
                SetErrBreak((L"VBox HostInterfaces: Host interface network was not found in registry (%s)! [3]", wszRegLocation));
        }
        while (0);

        if (hkeyConnection)
            RegCloseKey(hkeyConnection);
        if (hkeyNetwork)
            RegCloseKey(hkeyNetwork);

        /*
         * Now we are going to enumerate all network devices and
         * wait until we encounter the right device instance ID
         */

        HDEVINFO hDeviceInfo = INVALID_HANDLE_VALUE;
        BOOL fResult;

        do
        {
            DWORD ret = 0;
            GUID netGuid;
            SP_DEVINFO_DATA DeviceInfoData;
            DWORD index = 0;
            DWORD size = 0;

            /* initialize the structure size */
            DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

            /* copy the net class GUID */
            memcpy(&netGuid, &GUID_DEVCLASS_NET, sizeof (GUID_DEVCLASS_NET));

            /* return a device info set contains all installed devices of the Net class */
            hDeviceInfo = SetupDiGetClassDevs(&netGuid, NULL, NULL, DIGCF_PRESENT);
            if (hDeviceInfo == INVALID_HANDLE_VALUE)
            {
                logStringW(hModule, L"VBox HostInterfaces: SetupDiGetClassDevs failed (0x%08X)!", GetLastError());
                SetErrBreak(L"VBox HostInterfaces: Uninstallation failed!");
            }

            BOOL fFoundDevice = FALSE;

            /* enumerate the driver info list */
            while (TRUE)
            {
                WCHAR *pwszDeviceHwid;

                fResult = SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData);
                if (!fResult)
                {
                    if (GetLastError() == ERROR_NO_MORE_ITEMS)
                        break;
                    else
                    {
                        index++;
                        continue;
                    }
                }

                /* try to get the hardware ID registry property */
                fResult = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
                                                           &DeviceInfoData,
                                                           SPDRP_HARDWAREID,
                                                           NULL,
                                                           NULL,
                                                           0,
                                                           &size);
                if (!fResult)
                {
                    if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
                    {
                        index++;
                        continue;
                    }

                    pwszDeviceHwid = (WCHAR *)malloc(size);
                    if (pwszDeviceHwid)
                    {
                        fResult = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
                                                                   &DeviceInfoData,
                                                                   SPDRP_HARDWAREID,
                                                                   NULL,
                                                                   (PBYTE)pwszDeviceHwid,
                                                                   size,
                                                                   NULL);
                        if (!fResult)
                        {
                            free(pwszDeviceHwid);
                            pwszDeviceHwid = NULL;
                            index++;
                            continue;
                        }
                    }
                }
                else
                {
                    /* something is wrong.  This shouldn't have worked with a NULL buffer */
                    index++;
                    continue;
                }

                for (WCHAR *t = pwszDeviceHwid;
                     t && *t && t < &pwszDeviceHwid[size / sizeof(WCHAR)];
                     t += wcslen(t) + 1)
                {
                    if (!_wcsicmp(L"vboxtap", t))
                    {
                          /* get the device instance ID */
                          WCHAR wszDevID[MAX_DEVICE_ID_LEN];
                          if (CM_Get_Device_IDW(DeviceInfoData.DevInst,
                                                wszDevID, MAX_DEVICE_ID_LEN, 0) == CR_SUCCESS)
                          {
                              /* compare to what we determined before */
                              if (!wcscmp(wszDevID, wszPnPInstanceId))
                              {
                                  fFoundDevice = TRUE;
                                  break;
                              }
                          }
                    }
                }

                if (pwszDeviceHwid)
                {
                    free(pwszDeviceHwid);
                    pwszDeviceHwid = NULL;
                }

                if (fFoundDevice)
                    break;

                index++;
            }

            if (fFoundDevice)
            {
                fResult = SetupDiSetSelectedDevice(hDeviceInfo, &DeviceInfoData);
                if (!fResult)
                {
                    logStringW(hModule, L"VBox HostInterfaces: SetupDiSetSelectedDevice failed (0x%08X)!", GetLastError());
                    SetErrBreak(L"VBox HostInterfaces: Uninstallation failed!");
                }

                fResult = SetupDiCallClassInstaller(DIF_REMOVE, hDeviceInfo, &DeviceInfoData);
                if (!fResult)
                {
                    logStringW(hModule, L"VBox HostInterfaces: SetupDiCallClassInstaller (DIF_REMOVE) failed (0x%08X)!", GetLastError());
                    SetErrBreak(L"VBox HostInterfaces: Uninstallation failed!");
                }
            }
            else
                SetErrBreak(L"VBox HostInterfaces: Host interface network device not found!");
        }
        while (0);

        /* clean up the device info set */
        if (hDeviceInfo != INVALID_HANDLE_VALUE)
            SetupDiDestroyDeviceInfoList(hDeviceInfo);
    }
    while (0);
    return rc;
}
Esempio n. 3
0
BOOL
ConSrvWriteUserSettings(IN PCONSOLE_INFO ConsoleInfo,
                        IN DWORD ProcessId)
{
    BOOL GlobalSettings = (ConsoleInfo->ConsoleTitle[0] == L'\0');
    HKEY hKey;
    DWORD Storage = 0;

#define SetConsoleSetting(SettingName, SettingType, SettingSize, Setting, DefaultValue)         \
do {                                                                                            \
    if (GlobalSettings || (!GlobalSettings && (*(Setting) != (DefaultValue))))                  \
    {                                                                                           \
        RegSetValueExW(hKey, (SettingName), 0, (SettingType), (PBYTE)(Setting), (SettingSize)); \
    }                                                                                           \
    else                                                                                        \
    {                                                                                           \
        RegDeleteValue(hKey, (SettingName));                                                    \
    }                                                                                           \
} while (0)

    WCHAR szValueName[15];
    UINT i;

    if (!ConSrvOpenUserSettings(ProcessId,
                                ConsoleInfo->ConsoleTitle,
                                &hKey, KEY_WRITE,
                                TRUE))
    {
        return FALSE;
    }

    for (i = 0 ; i < sizeof(ConsoleInfo->Colors)/sizeof(ConsoleInfo->Colors[0]) ; ++i)
    {
        /*
         * Write only the new value if we are saving the global settings
         * or we are saving settings for a particular console, which differs
         * from the default ones.
         */
        swprintf(szValueName, L"ColorTable%02u", i);
        SetConsoleSetting(szValueName, REG_DWORD, sizeof(DWORD), &ConsoleInfo->Colors[i], s_Colors[i]);
    }

    SetConsoleSetting(L"HistoryBufferSize", REG_DWORD, sizeof(DWORD), &ConsoleInfo->HistoryBufferSize, 50);
    SetConsoleSetting(L"NumberOfHistoryBuffers", REG_DWORD, sizeof(DWORD), &ConsoleInfo->NumberOfHistoryBuffers, 4);

    Storage = ConsoleInfo->HistoryNoDup;
    SetConsoleSetting(L"HistoryNoDup", REG_DWORD, sizeof(DWORD), &Storage, FALSE);

    Storage = ConsoleInfo->QuickEdit;
    SetConsoleSetting(L"QuickEdit", REG_DWORD, sizeof(DWORD), &Storage, FALSE);

    Storage = ConsoleInfo->InsertMode;
    SetConsoleSetting(L"InsertMode", REG_DWORD, sizeof(DWORD), &Storage, TRUE);

    Storage = MAKELONG(ConsoleInfo->ScreenBufferSize.X, ConsoleInfo->ScreenBufferSize.Y);
    SetConsoleSetting(L"ScreenBufferSize", REG_DWORD, sizeof(DWORD), &Storage, MAKELONG(80, 300));

    Storage = MAKELONG(ConsoleInfo->ConsoleSize.X, ConsoleInfo->ConsoleSize.Y);
    SetConsoleSetting(L"WindowSize", REG_DWORD, sizeof(DWORD), &Storage, MAKELONG(80, 25));

    SetConsoleSetting(L"CursorSize", REG_DWORD, sizeof(DWORD), &ConsoleInfo->CursorSize, CSR_DEFAULT_CURSOR_SIZE);

    Storage = ConsoleInfo->ScreenAttrib;
    SetConsoleSetting(L"ScreenColors", REG_DWORD, sizeof(DWORD), &Storage, DEFAULT_SCREEN_ATTRIB);

    Storage = ConsoleInfo->PopupAttrib;
    SetConsoleSetting(L"PopupColors", REG_DWORD, sizeof(DWORD), &Storage, DEFAULT_POPUP_ATTRIB);

    RegCloseKey(hKey);
    return TRUE;
}
Esempio n. 4
0
File: GHJ.cpp Progetto: ruanzx/PSMJ
RC GHJ::Execute()
{
	RC rc = Initialize();
	if(rc!=SUCCESS)
	{
		return rc;
	} 

	DOUBLE cpuTimeBefore = 0;
	DOUBLE cpuTimeAfter = 0;
	DOUBLE cpuTime = 0;
	StopWatch stwTotalTime;
	StopWatch stwJoinTime;
	StopWatch stwPartitionTime;
	UINT64 totalTime = 0;
	UINT64 partitionTime = 0;
	UINT64 joinTime = 0;

	stwTotalTime.Start();
	stwPartitionTime.Start();
	cpuTimeBefore = GetCpuTime();

	PartitionTable(m_Params.RELATION_R_PATH, m_Params.R_KEY_POS, &m_InBuffer, m_BucketBuffer, m_FileHandle);

	/*************************************************************************/ 

	//再次对桶装配过程中需要的全局变量初始化 
	for(UINT partitionIndex=0; partitionIndex < m_PartitionNum; partitionIndex++)
	{   
		ResetPage(&m_BucketPage[partitionIndex], &m_BucketBuffer[partitionIndex]); 
	}

	PartitionTable(m_Params.RELATION_S_PATH, m_Params.S_KEY_POS, &m_InBuffer, m_BucketBuffer, m_FileHandle);

	partitionTime = stwPartitionTime.NowInMilliseconds();
	stwJoinTime.Start();

	HashJoin(&m_Pool);


	cpuTimeAfter = GetCpuTime(); 
	totalTime = stwTotalTime.NowInMilliseconds();
	joinTime = stwJoinTime.NowInMilliseconds();
	cpuTime = cpuTimeAfter - cpuTimeBefore;


	FILE *fp;   
	CHAR *reportFilePath = new CHAR[MAX_PATH];   
	LPWSTR tempReportPath = new TCHAR[MAX_PATH];
	swprintf(tempReportPath, MAX_PATH, L"%s%s", m_Params.WORK_SPACE_PATH, L"GHJ_Report.csv" ); 
	// convert file path to char  
	size_t  count = wcstombs(reportFilePath, tempReportPath, MAX_PATH); 

	CHAR *reportTitle = "Relation Size,Memory Size,Bucket Size,Partition,Read Buffer Size,Write Buffer Size,Total Execute Time(ms),Partition Time(ms),Join Time(ms),CPU Time\n";
	CHAR *reportContent = new CHAR[1024];
	sprintf(reportContent, "%d,%d,%.f,%d,%d,%d,%lld,%lld,%lld,%.f", 
		m_R_FileSize, 
		m_Params.BUFFER_POOL_SIZE/SSD_PAGE_SIZE, 
		m_BucketSize, 
		m_PartitionNum, 
		m_Params.READ_BUFFER_SIZE/SSD_PAGE_SIZE,
		m_Params.WRITE_BUFFER_SIZE/SSD_PAGE_SIZE, 
		totalTime, 
		partitionTime, 
		joinTime, 
		cpuTime);
	fp=fopen(reportFilePath, "w+b"); 
	fprintf(fp, reportTitle);
	fprintf(fp, reportContent);
	fclose(fp);

	delete reportFilePath;
	delete tempReportPath; 
	delete reportContent;

	//连接结束后 删除所有的临时文件 
	LPWSTR tempBucketName = new TCHAR[MAX_PATH];
	for(UINT partitionIndex=0;partitionIndex < m_PartitionNum;partitionIndex++)
	{
		swprintf_s(tempBucketName, MAX_PATH, L"%s%d%s.tmp", m_Params.WORK_SPACE_PATH, partitionIndex, m_Params.RELATION_R_NO_EXT);
		DeleteFile(tempBucketName);

		swprintf_s(tempBucketName, MAX_PATH, L"%s%d%s.tmp", m_Params.WORK_SPACE_PATH, partitionIndex, m_Params.RELATION_S_NO_EXT);
		DeleteFile(tempBucketName); 
	}

	delete tempBucketName;
	delete m_Pool.data;
	CloseHandle(m_hOutFile);

	ShowMB(L"GHJ done"); 

	return SUCCESS;
}
Esempio n. 5
0
static DWORD
ScConnectControlPipe(HANDLE *hPipe)
{
    DWORD dwBytesWritten;
    DWORD dwState;
    DWORD dwServiceCurrent = 0;
    NTSTATUS Status;
    WCHAR NtControlPipeName[MAX_PATH + 1];
    RTL_QUERY_REGISTRY_TABLE QueryTable[2];
    DWORD dwProcessId;

    /* Get the service number and create the named pipe */
    RtlZeroMemory(&QueryTable,
                  sizeof(QueryTable));

    QueryTable[0].Name = L"";
    QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_REQUIRED;
    QueryTable[0].EntryContext = &dwServiceCurrent;

    Status = RtlQueryRegistryValues(RTL_REGISTRY_CONTROL,
                                    L"ServiceCurrent",
                                    QueryTable,
                                    NULL,
                                    NULL);

    if (!NT_SUCCESS(Status))
    {
        ERR("RtlQueryRegistryValues() failed (Status %lx)\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    swprintf(NtControlPipeName, L"\\\\.\\pipe\\net\\NtControlPipe%u", dwServiceCurrent);

    if (!WaitNamedPipeW(NtControlPipeName, 30000))
    {
        ERR("WaitNamedPipe(%S) failed (Error %lu)\n", NtControlPipeName, GetLastError());
        return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
    }

    *hPipe = CreateFileW(NtControlPipeName,
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);
    if (*hPipe == INVALID_HANDLE_VALUE)
    {
        ERR("CreateFileW() failed for pipe %S (Error %lu)\n", NtControlPipeName, GetLastError());
        return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
    }

    dwState = PIPE_READMODE_MESSAGE;
    if (!SetNamedPipeHandleState(*hPipe, &dwState, NULL, NULL))
    {
        CloseHandle(*hPipe);
        *hPipe = INVALID_HANDLE_VALUE;
        return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
    }

    /* Pass the ProcessId to the SCM */
    dwProcessId = GetCurrentProcessId();
    WriteFile(*hPipe,
              &dwProcessId,
              sizeof(DWORD),
              &dwBytesWritten,
              NULL);

    TRACE("Sent Process ID %lu\n", dwProcessId);

    return ERROR_SUCCESS;
}
Esempio n. 6
0
void CArrayObject::sort( CCilVm* const pVm,
						const int32_t iNumArguments, 
						CVariable* pArguments )
{
	assert( iNumArguments >= 1 );
	CVariable& varThis = *pArguments;
	
	if( OperandType( pArguments->iOperandType ) != OPERAND_OBJECTREF
		|| pArguments->refObject->getRID() != pVm->getArrayObjectRID() )
	{
		//Throw TypeError
		pVm->throwException( &wstring( ERRORSTRING_TYPEERROR_ARRAY_TOSTRING ),
							&wstring( NAME_BUILTIN_ERROR_OBJECT ),
							ERROR_TYPEERROR_ARRAY_TOSTRING );
						return;
	}
		
	hash_map< wstring, CVariable >& map = varThis.refObject->getPropertyMap();
		
	hash_map< wstring, CVariable >::iterator itBegin = map.begin();
	hash_map< wstring, CVariable >::iterator itErase;
	hash_map< wstring, CVariable >::iterator itEnd = map.end();
		
	vector< CVariable >vecArray;
	vecArray.reserve( map.size() );
		
	//Dup entries to the vector
	while( itBegin != itEnd )
	{
		if( !(itBegin->second.iOperandFlag & OPERAND_FLAG_DONTENUM ) )
		{
			vecArray.push_back( itBegin->second );
			itErase = itBegin;
			++itBegin;
			map.erase( itErase );
		}
		else
			++itBegin;
	}
		
	vector< CVariable >::iterator itVecBegin = vecArray.begin();
	vector< CVariable >::iterator itVecEnd = vecArray.end();
	
	g_pVm = pVm;
	if( iNumArguments >= 2 )
	{
		pArguments++;
		if( pArguments->iOperandType == OPERAND_OBJECTREF
			&& pArguments->refObject->getCall() )
		{
			//Cmp function is given as 1st argument
			g_ridPredicater = pArguments->refObject->getCall();
			std::sort( itVecBegin, itVecEnd, CilPredicater );
		}
		else
		{
			//Fallback to regular sort.
			std::sort( itVecBegin, itVecEnd, Predicater );
		}
	}
	else
	{
		//Sort these inside the vector
		std::sort( itVecBegin, itVecEnd, Predicater );
	}
	wchar_t strIndex[ 16 ];
	uint32_t iIndexSrc = 0;
	uint32_t iIndexDest = 0;
	
	//Restore to the map
	itVecBegin = vecArray.begin();
	itVecEnd = vecArray.end();
	while( itVecBegin != itVecEnd )
	{
		//Skip storing UNDEFINED
		if( vecArray[ iIndexSrc ].iOperandType == OPERAND_UNDEFINED )
		{
			++itVecBegin;
			++iIndexSrc;
			continue;
		}
		swprintf( strIndex, 16, L"%d", iIndexDest );
		map[ strIndex ] = vecArray[ iIndexSrc ];
		
		++iIndexSrc;
		++iIndexDest;
		++itVecBegin;
	}
	
	pVm->pushEvalStack( varThis );
	return;
}
Esempio n. 7
0
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Renders the scene
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::Render()
{
	static float tt=0;

	if( m_DefaultGamepad.wPressedButtons & XINPUT_GAMEPAD_START )
	{
//		tt=this->m_fAppTime;
		angles[250]++;
	}

	if( m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_WHITE ] )
	{ zoomer_blend++; angles[251]++; }

	if( m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_BLACK] )
		angles[252]++;

	if( m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_X ] )
		angles[253]++;

	if( m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_B ] )
		angles[254]++;

	if( m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_A ] )
		angles[255]++;

#if 1

	float h0=
		-1*m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_LEFT_TRIGGER ]+
		1*m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_RIGHT_TRIGGER ];

	float h1=
		-1*m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_Y ]+
		1*m_DefaultGamepad.bPressedAnalogButtons [ XINPUT_GAMEPAD_X ];
/*
	int i=((int)angles[254])%animCount;
	animSet[i].speed=angles[0*8+0]+=m_DefaultGamepad.fY1*.2f;
	animSet[i].rotate=angles[0*8+1]+=m_DefaultGamepad.fX1*.2f;
	animSet[i].hue=angles[0*8+2]+=h0;

	i=((int)angles[255])%animCount;
	animSet[i].speed=angles[1*8+0]+=m_DefaultGamepad.fY2*.2f;
	animSet[i].rotate=angles[1*8+1]+=m_DefaultGamepad.fX2*.2f;
	animSet[i].hue=angles[1*8+2]+=h1;
*/
#endif
	demo_render(this->m_fAppTime-tt);
#if 0
	WCHAR buf1[256];
	WCHAR buf2[256];
	WCHAR buf3[256];


	swprintf(buf1, L"blend:%4d first %4d  second%4d ", zoomer_blend&3, ((int)angles[254])%animCount, ((int)angles[255])%animCount);
	swprintf(buf2, L"%4d %4d %4d", // %2x %2x %2x %2x %2x ", 
		(int)(4*angles[0*8+0]), 
		(int)(4*angles[0*8+1]), 
		(int)(4*angles[0*8+2]));
	swprintf(buf3, L"%4d %4d %4d", // %2x %2x %2x %2x %2x ", 
		(int)(4*angles[1*8+0]), 
		(int)(4*angles[1*8+1]), 
		(int)(4*angles[1*8+2]));

#endif
#if 0
	m_Font.Begin();
	//        m_Font.SetScaleFactors( 1.2f, 1.2f );
	//        m_Font.DrawText( 62, 45, 0xffffffff,  L"Magic Meat" );
	m_Font.SetScaleFactors( 1.0f, 1.0f );
	m_Font.DrawText( 62, 360, 0xffffffff, buf1, XBFONT_LEFT);
	m_Font.DrawText( 62, 400, 0xffff0000+0xff00, buf2, XBFONT_LEFT);
	m_Font.DrawText( 62, 440, 0xffff0000+0xff00, buf3, XBFONT_LEFT);

	swprintf(buf1, L"%4.4f", this->m_fAppTime);

	m_Font.DrawText( 568, 400, 0xffffff00, buf1, XBFONT_RIGHT );
	m_Font.DrawText( 568, 440, 0xffffff00, m_strFrameRate, XBFONT_RIGHT );
	m_Font.End();




	// Draw the on-screen audio level meters
	XBSound_DrawLevelMeters( m_pDSound, 0, 00.0f, 60.0f, 480.0f );
#endif
	// Present the scene
	m_pd3dDevice->Present( NULL, NULL, NULL, NULL );

	return S_OK;
}
Esempio n. 8
0
void NotifyPlayerOfMercDepartureAndPromptEquipmentPlacement( SOLDIERTYPE *pSoldier, BOOLEAN fAddRehireButton )
{
	// will tell player this character is leaving and ask where they want the equipment left
	CHAR16 sString[ 1024 ];
	BOOLEAN fInSector = FALSE;
//	INT16					zTownIDString[50];
	CHAR16				zShortTownIDString[ 50 ];

	// use YES/NO Pop up box, settup for particular screen
	SGPRect pCenteringRect= {0, 0, 640, 480};

	//GetSectorIDString( pSoldier->sSectorX, pSoldier->sSectorY, pSoldier->bSectorZ, zTownIDString, TRUE );

	GetShortSectorString( pSoldier->sSectorX ,pSoldier->sSectorY, zShortTownIDString );

	// Set string for generic button
	swprintf( gzUserDefinedButton1, L"%s", zShortTownIDString );


	pLeaveSoldier = pSoldier;

	if( pSoldier->fSignedAnotherContract == TRUE )
	{
		fAddRehireButton = FALSE;
	}

	if( pSoldier->fSignedAnotherContract == TRUE )
	{
		fAddRehireButton = FALSE;
	}

	if( pSoldier->ubWhatKindOfMercAmI != MERC_TYPE__AIM_MERC )
	{
		fAddRehireButton = FALSE;
	}

	//if the character is an RPC
	if( pSoldier->ubProfile >= FIRST_RPC && pSoldier->ubProfile < FIRST_NPC )
	{
		if( gMercProfiles[ pSoldier->ubProfile ].bSex == MALE )
		{
			swprintf( sString, pMercHeLeaveString[ 4 ], pSoldier->name, zShortTownIDString );
		}
		else
		{
			swprintf( sString, pMercSheLeaveString[ 4 ], pSoldier->name, zShortTownIDString );
		}
		fInSector = TRUE;
	}

	// check if drassen controlled
	else if( StrategicMap[  ( AIRPORT_X + ( MAP_WORLD_X * AIRPORT_Y ) ) ].fEnemyControlled == FALSE )
	{
		
		if( ( pSoldier->sSectorX == AIRPORT_X ) && ( pSoldier->sSectorY == AIRPORT_Y ) && ( pSoldier->bSectorZ == 0 ) )
		{
			if( gMercProfiles[ pSoldier->ubProfile ].bSex == MALE )
			{
				swprintf( sString, L"%s %s", pSoldier->name, pMercHeLeaveString[ 3 ] );
			}
			else
			{
				swprintf( sString, L"%s %s", pSoldier->name, pMercSheLeaveString[ 3 ] );
			}
			fInSector = TRUE;
		}
		else
		{
			// Set string for generic button
			swprintf( gzUserDefinedButton2, L"B13" );

			if( gMercProfiles[ pSoldier->ubProfile ].bSex == MALE )
			{
				swprintf( sString, pMercHeLeaveString[ 0 ], pSoldier->name, zShortTownIDString );
			}
			else
			{
				swprintf( sString, pMercSheLeaveString[ 0 ], pSoldier->name, zShortTownIDString );
			}
			
		}
	}
	else
	{
		if( ( pSoldier->sSectorX == OMERTA_LEAVE_EQUIP_SECTOR_X ) && ( pSoldier->sSectorY == OMERTA_LEAVE_EQUIP_SECTOR_Y ) && ( pSoldier->bSectorZ == 0 ) )
		{
			if( gMercProfiles[ pSoldier->ubProfile ].bSex == MALE )
			{
				swprintf( sString, L"%s %s", pSoldier->name, pMercHeLeaveString[ 2 ] );
			}
			else
			{
				swprintf( sString, L"%s %s", pSoldier->name, pMercSheLeaveString[ 2 ] );
			}
			fInSector = TRUE;
		}
		else
		{
			// Set string for generic button
			swprintf( gzUserDefinedButton2, L"A9" );

			if( gMercProfiles[ pSoldier->ubProfile ].bSex == MALE )
			{
				swprintf( sString, pMercHeLeaveString[ 1 ], pSoldier->name, zShortTownIDString );
			}
			else
			{
				swprintf( sString, pMercSheLeaveString[ 1 ], pSoldier->name, zShortTownIDString );
			}
		}
	}

	/// which screen are we in?
	if ( (guiTacticalInterfaceFlags & INTERFACE_MAPSCREEN ) )
	{
		if( fInSector == FALSE )
		{			
			// set up for mapscreen
			DoMapMessageBox( MSG_BOX_BASIC_STYLE, sString, MAP_SCREEN, ( UINT16 )( ( fAddRehireButton ? MSG_BOX_FLAG_GENERICCONTRACT : MSG_BOX_FLAG_GENERIC ) ), MercDepartEquipmentBoxCallBack );
		}
		else
		{
			DoMapMessageBox( MSG_BOX_BASIC_STYLE, sString, MAP_SCREEN, ( UINT16 )( ( fAddRehireButton ? MSG_BOX_FLAG_OKCONTRACT : MSG_BOX_FLAG_OK  ) ), MercDepartEquipmentBoxCallBack );
		}

	}
	else
	{
		if( fInSector == FALSE )
		{
			// set up for all otherscreens
			DoMessageBox(  MSG_BOX_BASIC_STYLE, sString,  guiCurrentScreen, ( UINT16 ) ( MSG_BOX_FLAG_USE_CENTERING_RECT | ( fAddRehireButton ? MSG_BOX_FLAG_GENERICCONTRACT : MSG_BOX_FLAG_GENERIC ) ),  MercDepartEquipmentBoxCallBack,  &pCenteringRect );
		}
		else
		{
			DoMessageBox(  MSG_BOX_BASIC_STYLE, sString,  guiCurrentScreen, ( UINT16 ) ( MSG_BOX_FLAG_USE_CENTERING_RECT | ( fAddRehireButton ? MSG_BOX_FLAG_OKCONTRACT : MSG_BOX_FLAG_OK  ) ) ,  MercDepartEquipmentBoxCallBack,  &pCenteringRect );
		}
	}
	
	if( pSoldier->fSignedAnotherContract == TRUE )
	{
		//fCurrentMercFired = FALSE;
	}

}
Esempio n. 9
0
// new tactical and mapscreen message system
void TacticalScreenMsg( UINT16 usColor, UINT8 ubPriority, STR16 pStringA, ... )
{
  // this function sets up the string into several single line structures
	
	ScrollStringStPtr pStringSt;
	UINT32 uiFont = TINYFONT1;
	UINT16 usPosition=0;
	UINT16 usCount=0;
	UINT16 usStringLength=0;
	UINT16 usCurrentSPosition=0;
	UINT16 usCurrentLookup=0;
	//wchar_t *pString;
	BOOLEAN fLastLine=FALSE;
  va_list argptr;

  wchar_t	DestString[512], DestStringA[ 512 ];
	//wchar_t *pStringBuffer;
  BOOLEAN fMultiLine=FALSE;
  ScrollStringStPtr pTempStringSt=NULL;
  WRAPPED_STRING *pStringWrapper=NULL;
  WRAPPED_STRING *pStringWrapperHead=NULL;
  BOOLEAN fNewString = FALSE;
	UINT16	usLineWidthIfWordIsWiderThenWidth=0;


	if( giTimeCompressMode > TIME_COMPRESS_X1 )
	{
		return;
	}

	if( fDisableJustForIan == TRUE && ubPriority != MSG_ERROR && ubPriority != MSG_INTERFACE )
	{
		return;
	}

	if( ubPriority == MSG_BETAVERSION )
	{
		usColor = BETAVERSION_COLOR;
		#ifndef JA2BETAVERSION
			#ifndef JA2TESTVERSION
				return;
			#endif
		#endif
		WriteMessageToFile( DestString );

	}

	if( ubPriority == MSG_TESTVERSION )
	{
		usColor = TESTVERSION_COLOR;

		#ifndef JA2TESTVERSION
			 return;
		#endif

		WriteMessageToFile( DestString );

	}


	if ( fFirstTimeInMessageSystem )
	{
		// Init display array!
		memset( gpDisplayList, 0, sizeof( gpDisplayList ) );
		fFirstTimeInMessageSystem = FALSE;
		//if(!(InitializeMutex(SCROLL_MESSAGE_MUTEX,"ScrollMessageMutex" )))
		//	return;
	}

	
	pStringSt=pStringS;
	while(GetNextString(pStringSt))
		    pStringSt=GetNextString(pStringSt);

	va_start(argptr, pStringA);       	// Set up variable argument pointer
	vswprintf(DestString, pStringA, argptr);	// process gprintf string (get output str)
	va_end(argptr);

	if ( ubPriority == MSG_DEBUG )
	{
		#ifndef _DEBUG
			return;
		#endif
		#ifdef JA2DEMO
			return;
		#endif
		usColor = DEBUG_COLOR;
		wcscpy( DestStringA, DestString );
		swprintf( DestString, L"Debug: %s", DestStringA );
		WriteMessageToFile( DestStringA );
	}

	if ( ubPriority == MSG_DIALOG )
	{
		usColor = DIALOGUE_COLOR;
	}

	if ( ubPriority == MSG_INTERFACE )
	{
		usColor = INTERFACE_COLOR;
	}



	pStringWrapperHead=LineWrap(uiFont, LINE_WIDTH, &usLineWidthIfWordIsWiderThenWidth, DestString);
  pStringWrapper=pStringWrapperHead;
	if(!pStringWrapper)
    return;
	
	fNewString = TRUE;
	while(pStringWrapper->pNextWrappedString!=NULL)
	{
	 if(!pStringSt)
	 {
    pStringSt=AddString(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority );
		fNewString = FALSE;
		pStringSt->pNext=NULL;
		pStringSt->pPrev=NULL;
    pStringS=pStringSt;
	 }
	 else
	 {
	  pTempStringSt=AddString(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority);
    fNewString = FALSE;
		pTempStringSt->pPrev=pStringSt;
	  pStringSt->pNext=pTempStringSt;
	  pStringSt=pTempStringSt;
	  pTempStringSt->pNext=NULL;
	 }
   pStringWrapper=pStringWrapper->pNextWrappedString;
	}
  pTempStringSt=AddString(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority );
	if(pStringSt)
	{
	 pStringSt->pNext=pTempStringSt;
	 pTempStringSt->pPrev=pStringSt;
	 pStringSt=pTempStringSt;
	 pStringSt->pNext=NULL;
	}
  else
	{
		pStringSt=pTempStringSt;
		pStringSt->pNext=NULL;
		pStringSt->pPrev=NULL;
    pStringS=pStringSt;
	}
	
	// clear up list of wrapped strings
	ClearWrappedStrings( pStringWrapperHead );

 //LeaveMutex(SCROLL_MESSAGE_MUTEX, __LINE__, __FILE__);
 return;
} 
void AddCommonInfoToBox(void)
{
	CHAR16 wString[ 64 ];
	UINT32 hStringHandle = 0;
	BOOLEAN fUnknownSAMSite = FALSE;
	UINT8 ubMilitiaTotal = 0;
	UINT8 ubNumEnemies;


	switch( SECTOR( bCurrentTownMineSectorX, bCurrentTownMineSectorY ) )
	{
		case SEC_D2: //Chitzena SAM
			if( !fSamSiteFound[ SAM_SITE_ONE ] )
				fUnknownSAMSite = TRUE;
			break;
		case SEC_D15: //Drassen SAM
			if( !fSamSiteFound[ SAM_SITE_TWO ] )
				fUnknownSAMSite = TRUE;
			break;
		case SEC_I8: //Cambria SAM
			if( !fSamSiteFound[ SAM_SITE_THREE ] )
				fUnknownSAMSite = TRUE;
			break;
		// SAM Site 4 in Meduna is within town limits, so it's always controllable
		default:
			break;
	}


	// in sector where militia can be trained,
	// control of the sector matters, display who controls this sector.  Map brightness no longer gives this!
	if ( MilitiaTrainingAllowedInSector( bCurrentTownMineSectorX, bCurrentTownMineSectorY, 0 ) && !fUnknownSAMSite )
	{
		// controlled:
		swprintf( wString, L"%s:", pwMiscSectorStrings[ 4 ] );
		AddMonoString( &hStringHandle, wString );

		// No/Yes
		swprintf( wString, L"%s", pwMiscSectorStrings[ ( StrategicMap[ CALCULATE_STRATEGIC_INDEX( bCurrentTownMineSectorX, bCurrentTownMineSectorY ) ].fEnemyControlled ) ? 6 : 5 ] );
		AddSecondColumnMonoString( &hStringHandle, wString );


		// militia - is there any?
		swprintf( wString, L"%s:", pwTownInfoStrings[ 11 ] );
		AddMonoString( &hStringHandle, wString );

		ubMilitiaTotal = CountAllMilitiaInSector(bCurrentTownMineSectorX, bCurrentTownMineSectorY);
		if (ubMilitiaTotal > 0)
		{
			// some militia, show total & their breakdown by level
	 		swprintf( wString, L"%d  (%d/%d/%d)", ubMilitiaTotal,
												MilitiaInSectorOfRank(bCurrentTownMineSectorX, bCurrentTownMineSectorY, GREEN_MILITIA),
												MilitiaInSectorOfRank(bCurrentTownMineSectorX, bCurrentTownMineSectorY, REGULAR_MILITIA),
												MilitiaInSectorOfRank(bCurrentTownMineSectorX, bCurrentTownMineSectorY, ELITE_MILITIA));
			AddSecondColumnMonoString( &hStringHandle, wString );
		}
		else
		{
			// no militia: don't bother displaying level breakdown
			wcscpy( wString, L"0");
			AddSecondColumnMonoString( &hStringHandle, wString );
		}


		// percentage of current militia squad training completed
		swprintf( wString, L"%s:", pwTownInfoStrings[ 10 ] );
		AddMonoString( &hStringHandle, wString );
		swprintf( wString, L"%d%%%%", SectorInfo[ SECTOR( bCurrentTownMineSectorX, bCurrentTownMineSectorY ) ].ubMilitiaTrainingPercentDone );
		AddSecondColumnMonoString( &hStringHandle, wString );
	}


	// enemy forces
	swprintf( wString, L"%s:", pwMiscSectorStrings[ 0 ] );
	AddMonoString( &hStringHandle, wString );

	// how many are there, really?
	ubNumEnemies = NumEnemiesInSector( bCurrentTownMineSectorX, bCurrentTownMineSectorY );
	
	switch ( WhatPlayerKnowsAboutEnemiesInSector( bCurrentTownMineSectorX, bCurrentTownMineSectorY ) )
	{
		case KNOWS_NOTHING:
			// show "Unknown"
			wcscpy(wString, pwMiscSectorStrings[ 3 ] );
			break;

		case KNOWS_THEYRE_THERE:
			// if there are any there
			if ( ubNumEnemies > 0 )
			{
				// show "?", but not exactly how many
				wcscpy(wString, L"?" );
			}
			else
			{
				// we know there aren't any (or we'd be seing them on map, too)
				wcscpy(wString, L"0" );
			}
			break;

		case KNOWS_HOW_MANY:
			// show exactly how many
			swprintf( wString, L"%d", ubNumEnemies );
			break;
	}

	AddSecondColumnMonoString( &hStringHandle, wString );
}
Esempio n. 11
0
LPWSTR TempFileName(LPCWSTR fileName)
// generate a unique temporary filename
// creates a sub-directory in TEMP and uses fileName as a guide for the
// filename
// returns name of temporary directory if fileName is NULL
	{
	static WCHAR tmpPath[MAX_PATH]={'\0'};
	static WCHAR tmpFileName[MAX_PATH]={'\0'};
	HANDLE hFile;
	if (*tmpPath=='\0')
		{
		// first time called so generate temporary directory
		// first get TEMP directory
#ifdef _UNICODE
		WCHAR tmpDir[MAX_PATH];
		GetTempPathW(MAX_PATH,tmpDir);
		// now create a unique sub-directory
		for (WORD i=0; i<10000;i++)
			{
			(void)swprintf(tmpPath, sizeof(tmpPath), L"%S/MKS%d",tmpDir,i);
			if (::CreateDirectoryW(tmpPath,NULL)) break;
			}
#else
		char tempPath[MAX_PATH];
		char tmpDir[MAX_PATH];
		GetTempPath(MAX_PATH,tempPath);
		// now create a unique sub-directory
		for (WORD i=0; i<10000;i++)
			{
			sprintf(tmpDir,"%s/MKS%d",tempPath,i);
			if (::CreateDirectory(tmpDir,NULL)) break;
			}
		::MultiByteToWideChar(CP_OEMCP, 0, tmpDir, -1, tmpPath, MAX_PATH);
#endif
		}
	if (fileName)
		{
		/* Find the last backslash */
		int index = 0;
		for(size_t i=0;i<wcslen(fileName);i++) {
			if(fileName[i] == '/'
			   ||
			   fileName[i] == '\\')
				index = i;
		}
		if(index > 0)
			fileName = &fileName[index+1];

		swprintf(tmpFileName,
#ifndef __GNUC__
			sizeof(tmpFileName),
#endif
			L"%s/%s",tmpPath,fileName);
		for (WORD i=0; i<10000;i++)
			{
			hFile = ::MakeSISOpenFile(tmpFileName, GENERIC_READ, OPEN_EXISTING);
			if (hFile==INVALID_HANDLE_VALUE) break;
			CloseHandle(hFile);
			swprintf(tmpFileName,
#ifndef __GNUC__
				sizeof(tmpFileName),
#endif
				L"%s/%s%d",tmpPath,fileName,i);
			}
		/** Convert backslash to underscore for the generated filename */
/*
		WCHAR *tmp = &tmpFileName[0];
		while(*tmp) {
			if(*tmp == '/') {
				*tmp = '\\';
			}
			tmp++;
		}
*/
		}
	else
		wcscpy(tmpFileName,tmpPath);
	return tmpFileName;
	}
// adds text to mine info box
void AddTextToMineBox( void )
{
	UINT8 ubMineIndex;
	UINT8 ubTown;
	UINT32 hStringHandle;
	CHAR16 wString[ 64 ];


	ubMineIndex = GetMineIndexForSector( bCurrentTownMineSectorX, bCurrentTownMineSectorY );

	// name of town followed by "mine"
	swprintf( wString, L"%s %s", pTownNames[ GetTownAssociatedWithMine( ubMineIndex ) ], pwMineStrings[ 0 ] );
	AddMonoString( &hStringHandle, wString );

	// blank line
	AddMonoString( &hStringHandle, L"" );


	// sector
	AddSectorToBox();

	// mine status
	swprintf( wString, L"%s:", pwMineStrings[ 9 ]);
	AddMonoString( &hStringHandle, wString );

	// check if mine is empty (abandoned) or running out
	if (gMineStatus[ ubMineIndex ].fEmpty)
	{
		// abandonded
		wcscpy( wString, pwMineStrings[ 5 ] );
	}
	else
	if (gMineStatus[ ubMineIndex ].fShutDown)
	{
		// shut down
		wcscpy( wString, pwMineStrings[ 6 ] );
	}
	else
	if (gMineStatus[ ubMineIndex ].fRunningOut)
	{
		// running out
		wcscpy( wString, pwMineStrings[ 7 ] );
	}
	else
	{
		// producing
		wcscpy( wString, pwMineStrings[ 8 ] );
	}
	AddSecondColumnMonoString( &hStringHandle, wString );


	// if still producing
	if (!gMineStatus[ ubMineIndex ].fEmpty)
	{
		// current production
		swprintf( wString, L"%s:", pwMineStrings[ 3 ]);
		AddMonoString( &hStringHandle, wString );

		swprintf( wString, L"%d", PredictDailyIncomeFromAMine( ubMineIndex ) );
		InsertCommasForDollarFigure( wString );
		InsertDollarSignInToString( wString );
		AddSecondColumnMonoString( &hStringHandle, wString );


		// potential production
		swprintf( wString, L"%s:", pwMineStrings[ 4 ]);
		AddMonoString( &hStringHandle, wString );

		swprintf( wString, L"%d", GetMaxDailyRemovalFromMine( ubMineIndex ) );
		InsertCommasForDollarFigure( wString );
		InsertDollarSignInToString( wString );
		AddSecondColumnMonoString( &hStringHandle, wString );


		// if potential is not nil
		if (GetMaxPeriodicRemovalFromMine(ubMineIndex) > 0)
		{
			// production rate (current production as a percentage of potential production)
			swprintf( wString, L"%s:", pwMineStrings[ 10 ]);
			AddMonoString( &hStringHandle, wString );
			swprintf( wString, L"%d%%%%", (PredictDailyIncomeFromAMine(ubMineIndex) * 100 ) / GetMaxDailyRemovalFromMine(ubMineIndex) );
			AddSecondColumnMonoString( &hStringHandle, wString );
		}


		// town control percentage
		swprintf( wString, L"%s:", pwMineStrings[ 12 ]);
		AddMonoString( &hStringHandle, wString );
		swprintf( wString, L"%d%%%%", (GetTownSectorsUnderControl( gMineLocation[ ubMineIndex ].bAssociatedTown ) *  100) / GetTownSectorSize( gMineLocation[ ubMineIndex ].bAssociatedTown ));
		AddSecondColumnMonoString( &hStringHandle, wString );

		ubTown = gMineLocation[ ubMineIndex ].bAssociatedTown;
		if( gTownLoyalty[ ubTown ].fStarted && gfTownUsesLoyalty[ ubTown ])
		{
			// town loyalty percentage
			swprintf( wString, L"%s:", pwMineStrings[ 13 ]);
			AddMonoString( &hStringHandle, wString );
			swprintf( wString, L"%d%%%%", gTownLoyalty[ gMineLocation[ ubMineIndex ].bAssociatedTown ].ubRating);
			AddSecondColumnMonoString( &hStringHandle, wString );
		}

/* gradual monster infestation concept was ditched, now simply IN PRODUCTION or SHUT DOWN
		// percentage of miners working
		swprintf( wString, L"%s:", pwMineStrings[ 14 ]);
		AddMonoString( &hStringHandle, wString );
		swprintf( wString, L"%d%%%%", gubMonsterMineInfestation[ gMineStatus[ ubMineIndex ].bMonsters ]);
		AddSecondColumnMonoString( &hStringHandle, wString );
*/

		// ore type (silver/gold
		swprintf( wString, L"%s:", pwMineStrings[ 11 ]);
		AddMonoString( &hStringHandle, wString );
		AddSecondColumnMonoString( &hStringHandle, (gMineStatus[ubMineIndex].ubMineType == SILVER_MINE) ? pwMineStrings[ 1 ] : pwMineStrings[ 2 ] );
	}


#ifdef _DEBUG
	// dollar amount remaining in mine
	wcscpy( wString, L"Remaining (DEBUG):");
	AddMonoString( &hStringHandle, wString );

	swprintf( wString, L"%d", GetTotalLeftInMine( ubMineIndex ) );
	InsertCommasForDollarFigure( wString );
	InsertDollarSignInToString( wString );
	AddSecondColumnMonoString( &hStringHandle, wString );
#endif

}
// adds text to town info box
void AddTextToTownBox( void )
{
	UINT32 hStringHandle = 0;
	CHAR16 wString[ 64 ];
	UINT8 ubTownId = 0;
	UINT16 usTownSectorIndex;
	INT16 sMineSector = 0;


	// remember town id
	ubTownId = GetTownIdForSector( bCurrentTownMineSectorX, bCurrentTownMineSectorY );
	Assert((ubTownId >= FIRST_TOWN) && (ubTownId < NUM_TOWNS));

	usTownSectorIndex = SECTOR( bCurrentTownMineSectorX, bCurrentTownMineSectorY );

	switch( usTownSectorIndex )
	{
		case SEC_B13:
			AddMonoString( &hStringHandle, pLandTypeStrings[ DRASSEN_AIRPORT_SITE ] );
			break;
		case SEC_F8:
			AddMonoString( &hStringHandle, pLandTypeStrings[ CAMBRIA_HOSPITAL_SITE ] );
			break;
		case SEC_J9: //Tixa
			if( !fFoundTixa )
				AddMonoString( &hStringHandle, pLandTypeStrings[ SAND ] );
			else
				AddMonoString( &hStringHandle, pTownNames[ TIXA ] );
			break;
		case SEC_K4: //Orta
			if( !fFoundOrta )
				AddMonoString( &hStringHandle, pLandTypeStrings[ SWAMP ] );
			else
				AddMonoString( &hStringHandle, pTownNames[ ORTA ] );
			break;
		case SEC_N3:
			AddMonoString( &hStringHandle, pLandTypeStrings[ MEDUNA_AIRPORT_SITE ] );
			break;
		default:
			if( usTownSectorIndex == SEC_N4 && fSamSiteFound[ SAM_SITE_FOUR ] )
			{	//Meduna's SAM site
				AddMonoString( &hStringHandle, pLandTypeStrings[ MEDUNA_SAM_SITE ] );
			}
			else
			{ // town name
				swprintf( wString, L"%s", pTownNames[ ubTownId ] );
				AddMonoString( &hStringHandle, wString );
			}
			break;
	}
	// blank line
	AddMonoString( &hStringHandle, L"" );

	// sector
	AddSectorToBox();

	// town size
	swprintf( wString, L"%s:", pwTownInfoStrings[ 0 ] );
	AddMonoString( &hStringHandle, wString );
	swprintf( wString, L"%d",  GetTownSectorSize( ubTownId ) );
	AddSecondColumnMonoString( &hStringHandle, wString );

	// main facilities
	swprintf( wString, L"%s:", pwTownInfoStrings[ 8 ] );
	AddMonoString( &hStringHandle, wString );
	wcscpy(wString, L"");
	GetSectorFacilitiesFlags( bCurrentTownMineSectorX, bCurrentTownMineSectorY, wString );
	AddSecondColumnMonoString( &hStringHandle, wString );

	// the concept of control is only meaningful in sectors where militia can be trained
	if ( MilitiaTrainingAllowedInSector( bCurrentTownMineSectorX, bCurrentTownMineSectorY, 0 ) )
	{
		// town control
		swprintf( wString, L"%s:", pwTownInfoStrings[ 2 ] );
		AddMonoString( &hStringHandle, wString );
		swprintf( wString, L"%d%%%%",  (GetTownSectorsUnderControl( ubTownId ) * 100) / GetTownSectorSize( ubTownId ));
		AddSecondColumnMonoString( &hStringHandle, wString );
	}

	// the concept of town loyalty is only meaningful in towns where loyalty is tracked
	if( gTownLoyalty[ ubTownId ].fStarted && gfTownUsesLoyalty[ ubTownId ])
	{
		// town loyalty
		swprintf( wString, L"%s:", pwTownInfoStrings[ 5 ] );
		AddMonoString( &hStringHandle, wString );
		swprintf( wString, L"%d%%%%", gTownLoyalty[ ubTownId ].ubRating );
		AddSecondColumnMonoString( &hStringHandle, wString );
	}

	// if the town has a mine
	sMineSector = GetMineSectorForTown( ubTownId );
	if( sMineSector != -1 )
	{
		// Associated Mine: Sector
	  swprintf( wString, L"%s:",  pwTownInfoStrings[ 4 ] );
		AddMonoString( &hStringHandle, wString );
	  GetShortSectorString( ( INT16 )( sMineSector % MAP_WORLD_X ), ( INT16 )( sMineSector / MAP_WORLD_X ), wString );
		AddSecondColumnMonoString( &hStringHandle, wString );
	}
}
double getCpuUsage()
{ 
	SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo; 
	SYSTEM_TIME_INFORMATION SysTimeInfo; 
	SYSTEM_BASIC_INFORMATION SysBaseInfo; 
 
	LONG status; 

	//change char** to lpcwstr
	char a[] = "ntdll";
	WCHAR wsz[64]; 
	swprintf(wsz, L"%S", a);
	LPCWSTR ntdll = wsz;

	NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(GetModuleHandle(ntdll),"NtQuerySystemInformation");
	// get number of processors in the system 
	status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL); 
	if (status != NO_ERROR) 
		return -1;
 
	if (!NtQuerySystemInformation) 
		return -1;
 
	// get number of processors in the system 
	status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL); 
	if (status != NO_ERROR) 
		return -1;
 
	// get new system time 
	status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0); 
	if (status!=NO_ERROR) 
		return -1;
 
	// get new CPU's idle time 
	status =NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL); 
	if (status != NO_ERROR) 
		return -1;
 
	if ( m_iNumberProcessors != SysBaseInfo.bKeNumberProcessors)
	{
		//save
		m_iNumberProcessors = SysBaseInfo.bKeNumberProcessors;
		//if sppi not null clear
		if (m_pSPPI != NULL) delete []m_pSPPI;
		if (m_PUT != NULL) delete []m_PUT;
		//malloc and point
		m_pSPPI = new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[m_iNumberProcessors];
		m_PUT = new m_PROCESSORS_USE_TIME[m_iNumberProcessors];
	}
 
	// get ProcessorPer time 
	status =NtQuerySystemInformation(SystemProcessorPerformanceInformation, m_pSPPI, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * m_iNumberProcessors, NULL); 
	if (status != NO_ERROR) 
		return -1;
 
	// if it's a first call - skip it 
	if (liOldIdleTime.QuadPart != 0) 
	{ 
		// CurrentValue = NewValue - OldValue 
		dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime); 
 
		dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
 
		// CurrentCpuIdle = IdleTime / SystemTime 
		dbIdleTime = dbIdleTime / dbSystemTime;
 
		// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors 
		dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors;
 
		//calc Processors
		for (int i = 0; i < m_iNumberProcessors; i++)
		{
			m_PUT[i].dbCurrentTime = Li2Double(m_pSPPI[i].KernelTime) + Li2Double(m_pSPPI[i].UserTime) + 
										Li2Double(m_pSPPI[i].DpcTime) + Li2Double(m_pSPPI[i].InterruptTime) - m_PUT[i].dbOldCurrentTime;
			m_PUT[i].dbIdleTime = Li2Double(m_pSPPI[i].IdleTime) - m_PUT[i].dbOldIdleTime;
 
			// CurrentCpuIdle = IdleTime / SystemTime 
			m_PUT[i].dbIdleTime = m_PUT[i].dbIdleTime / m_PUT[i].dbCurrentTime;
 
			// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors 
			m_PUT[i].dbIdleTime = 100.0 - m_PUT[i].dbIdleTime * 100.0;
 
		}
	}
 
	// store new CPU's idle and system time 
	liOldIdleTime = SysPerfInfo.liIdleTime; 
	liOldSystemTime = SysTimeInfo.liKeSystemTime;
 
	for (int i = 0; i < m_iNumberProcessors; i++)
	{
		m_PUT[i].dbOldCurrentTime = Li2Double(m_pSPPI[i].KernelTime) + Li2Double(m_pSPPI[i].UserTime) + 
										Li2Double(m_pSPPI[i].DpcTime) + Li2Double(m_pSPPI[i].InterruptTime);
 
		m_PUT[i].dbOldIdleTime = Li2Double(m_pSPPI[i].IdleTime);
	}
 
	return dbIdleTime;
}
Esempio n. 15
0
/***************************************************************************
 *      Construct Array object
 ***************************************************************************/
void CArrayObject::ctor( CCilVm* const pVm,
										   const int32_t iNumArguments, 
										   CVariable* pArguments )
{
	assert( pVm != NULL );
	assert( iNumArguments >= 1 );

	//Initialize this object
	CVariable& var = *pArguments;
	pArguments++;
	assert( OperandType( var.iOperandType ) == OPERAND_OBJECTREF );

	//Set prototype: Array prototype object
	var.refObject->setPrototypeObject( 
		&pVm->getPrototypeObject( pVm->getArrayObjectRID() ) );

	//setProperty Accessor
	var.refObject->setPropertyAccessor( STRING_INTERNAL_LENGTH,
										lengthAccessor );
	//setProperty Accessor
	var.refObject->setPropertyAccessor( STRING_PROPERTY_INTERNAL_ANY,
										anyAccessor );

	if( iNumArguments == 2 )
	{
		//Special case when only 1 argument is given

		int32_t iArrayLength = iNumArguments - 1;
		OPERAND_TYPE type = pArguments->getPrimitiveType();
		if( type != OPERAND_STRING )
		{
			//Argument is a number
			int32_t iSize = pArguments->toInt();
			if( iSize >= MAX_ARRAYLENGTH )
			{
				//Throw TypeError
				pVm->throwException( &wstring( ERRORSTRING_OUTOFMEMORY ),
					&wstring( NAME_BUILTIN_ERROR_OBJECT ),
					ERROR_OUT_OF_MEMORY );

				return;
			}
			else if( iSize < 0 )
			{
				//Throw TypeError
				pVm->throwException( &wstring( ERRORSTRING_ARRAY_LENGTH ),
					&wstring( NAME_BUILTIN_ERROR_OBJECT ),
					ERROR_ARRAY_LENGTH );

				return;
			}
			iArrayLength = iSize;
		}
		else
		{
			//Store initializers to the array
			wchar_t strBuffer[ 22 ];		//22=max value width of longlong
			int32_t i = 0;
			for( i = 0; i < iNumArguments - 1; ++i )
			{
				//Argument: 1) value of the property
				swprintf( strBuffer, 22, L"%d", i );
				var.refObject->setProperty( strBuffer, *pArguments );
				pArguments++;
			}
		}

		//Just set length
		//Set to ".lengh"
		CVariable varLength( (int32_t)iArrayLength,
					  OPERAND_FLAG( OPERAND_FLAG_DONTDELETE | OPERAND_FLAG_DONTENUM ) );
		var.refObject->setProperty( STRING_PROPERTY_INTERNAL_LENGTH, varLength );
	}
	else
	{
		//Store initializers to the array
		wchar_t strBuffer[ 22 ];		//22=max value width of longlong
		int32_t i = 0;
		for( i = 0; i < iNumArguments - 1; ++i )
		{
			//Argument: 1) value of the property
			swprintf( strBuffer, 22, L"%d", i );
			var.refObject->setProperty( strBuffer, *pArguments );
			pArguments++;
		}

		//Set to ".lengh"
		CVariable varLength( (int32_t)iNumArguments - 1,
					  OPERAND_FLAG( OPERAND_FLAG_DONTDELETE | OPERAND_FLAG_DONTENUM ) ); 
		var.refObject->setProperty( STRING_PROPERTY_INTERNAL_LENGTH, varLength );
	}

	return;
}
Esempio n. 16
0
void MapScreenMessage( UINT16 usColor, UINT8 ubPriority, STR16 pStringA, ... )
{
  // this function sets up the string into several single line structures
	 
	ScrollStringStPtr pStringSt;
	UINT32 uiFont = MAP_SCREEN_MESSAGE_FONT;
	UINT16 usPosition=0;
	UINT16 usCount=0;
	UINT16 usStringLength=0;
	UINT16 usCurrentSPosition=0;
	UINT16 usCurrentLookup=0;
	//wchar_t *pString;
	BOOLEAN fLastLine=FALSE;
  va_list argptr;
  wchar_t	DestString[512], DestStringA[ 512 ];
	//wchar_t *pStringBuffer;
  BOOLEAN fMultiLine=FALSE;
  WRAPPED_STRING *pStringWrapper=NULL;
  WRAPPED_STRING *pStringWrapperHead=NULL;
  BOOLEAN fNewString = FALSE;
	UINT16	usLineWidthIfWordIsWiderThenWidth;

	if( fDisableJustForIan == TRUE )
	{
		if( ubPriority == MSG_BETAVERSION )
		{
			return;
		}
		else if( ubPriority == MSG_TESTVERSION )
		{
			return;
		}
		else if ( ubPriority == MSG_DEBUG )
		{
			return;
		}
	}

	if( ubPriority == MSG_BETAVERSION )
	{
		usColor = BETAVERSION_COLOR;
		#ifndef JA2BETAVERSION
			#ifndef JA2TESTVERSION
				return;
			#endif
		#endif

		WriteMessageToFile( DestString );
	}

	if( ubPriority == MSG_TESTVERSION )
	{
		usColor = TESTVERSION_COLOR;

		#ifndef JA2TESTVERSION
			 return;
		#endif
		WriteMessageToFile( DestString );
	}
	// OK, check if we are ani imeediate feedback message, if so, do something else!
	if ( ubPriority == MSG_UI_FEEDBACK )
	{
		va_start(argptr, pStringA);       	// Set up variable argument pointer
		vswprintf(DestString, pStringA, argptr);	// process gprintf string (get output str)
		va_end(argptr);

		BeginUIMessage( DestString );
		return;
	}

	if ( ubPriority == MSG_SKULL_UI_FEEDBACK )
	{
		va_start(argptr, pStringA);       	// Set up variable argument pointer
		vswprintf(DestString, pStringA, argptr);	// process gprintf string (get output str)
		va_end(argptr);

		InternalBeginUIMessage( TRUE, DestString );
		return;
	}

	// check if error
	if ( ubPriority == MSG_ERROR )
	{
		va_start(argptr, pStringA);       	// Set up variable argument pointer
		vswprintf(DestString, pStringA, argptr);	// process gprintf string (get output str)
		va_end(argptr);

		swprintf( DestStringA, L"DEBUG: %s", DestString );

		BeginUIMessage( DestStringA );
		WriteMessageToFile( DestStringA );

		return;
	}


		// OK, check if we are an immediate MAP feedback message, if so, do something else!
	if ( ( ubPriority == MSG_MAP_UI_POSITION_UPPER  ) ||
			 ( ubPriority == MSG_MAP_UI_POSITION_MIDDLE ) ||
			 ( ubPriority == MSG_MAP_UI_POSITION_LOWER  ) )
	{
		va_start(argptr, pStringA);       	// Set up variable argument pointer
		vswprintf(DestString, pStringA, argptr);	// process gprintf string (get output str)
		va_end(argptr);

		BeginMapUIMessage( ubPriority, DestString );
		return;
	}


	if ( fFirstTimeInMessageSystem )
	{
		// Init display array!
		memset( gpDisplayList, 0, sizeof( gpDisplayList ) );
		fFirstTimeInMessageSystem = FALSE;
		//if(!(InitializeMutex(SCROLL_MESSAGE_MUTEX,"ScrollMessageMutex" )))
		//	return;
	}

	
	pStringSt=pStringS;
	while(GetNextString(pStringSt))
		    pStringSt=GetNextString(pStringSt);

	va_start(argptr, pStringA);       	// Set up variable argument pointer
	vswprintf(DestString, pStringA, argptr);	// process gprintf string (get output str)
	va_end(argptr);

	if ( ubPriority == MSG_DEBUG )
	{
		#ifndef _DEBUG
			return;
		#endif
		#ifdef JA2DEMO
			return;
		#endif
		usColor = DEBUG_COLOR;
		wcscpy( DestStringA, DestString );
		swprintf( DestString, L"Debug: %s", DestStringA );
	}

	if ( ubPriority == MSG_DIALOG )
	{
		usColor = DIALOGUE_COLOR;
	}

	if ( ubPriority == MSG_INTERFACE )
	{
		usColor = INTERFACE_COLOR;
	}

	pStringWrapperHead=LineWrap(uiFont, MAP_LINE_WIDTH, &usLineWidthIfWordIsWiderThenWidth, DestString);
  pStringWrapper=pStringWrapperHead;
	if(!pStringWrapper)
    return;
	
	fNewString = TRUE;

	while(pStringWrapper->pNextWrappedString!=NULL)
	{
		AddStringToMapScreenMessageList(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority );
		fNewString = FALSE;

		pStringWrapper=pStringWrapper->pNextWrappedString;
	}

  AddStringToMapScreenMessageList(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority );


	// clear up list of wrapped strings
	ClearWrappedStrings( pStringWrapperHead );

	// play new message beep
	//PlayNewMessageSound( );

	MoveToEndOfMapScreenMessageList( );

	//LeaveMutex(SCROLL_MESSAGE_MUTEX, __LINE__, __FILE__);
}
Esempio n. 17
0
/***************************************************************************
 *      join property
 ***************************************************************************/
void CArrayObject::join( CCilVm* const pVm,
									const int32_t iNumArguments, 
									CVariable* pArguments )

{
	assert( iNumArguments >= 1 );
	CVariable& varThis = *pArguments;

	wstring sSeparator = wstring( STRING_INTERNAL_JOIN_DEFAULT_SEPARATOR );

	//Set up separator string
	if( iNumArguments > 1 )
	{
		//Set new separator
		pArguments ++;
		sSeparator = *pArguments->toString( pVm );
	}

	//Initialize destination variable in the eval stack
	pVm->pushEvalStackUndefined();
	
	CVariable& var = pVm->getEvalStackFirstEntry();
	var.iOperandType = OPERAND_STRING;
	var.pString = new wstring(L"");

	uint32_t iIndex = 0;
	uint32_t iLength = 0;
	hash_map< wstring, CVariable >::iterator itStart = varThis.refObject->getPropertyMap().begin();
	hash_map< wstring, CVariable >::iterator itEnd = varThis.refObject->getPropertyMap().end();
	while( itStart != itEnd )
	{
		bool bDigit = CheckArrayIndex( itStart->first );
		if( bDigit )
			iLength ++;
		itStart++;
	}
	
	wchar_t strIndex[ 16 ];

	while( iLength )
	{
		swprintf( strIndex, 16, L"%d", iIndex );
		CVariable* pvar;
		pvar = varThis.refObject->lookupProperty( strIndex );
		if( iIndex )
			var.pString->append( sSeparator );
		iIndex++;
		if( pvar )
		{
			CVariable varTmp = *pvar;
			
			//To eliminate recursive death
			if( varThis.refObject != varTmp.refObject ||
				varTmp.iOperandType != OPERAND_OBJECTREF )
			{
				varTmp.convertToString( pVm );
				var.pString->append( *varTmp.pString );
			}
			iLength--;
		}
	}
	
	return;
}
Esempio n. 18
0
NTSTATUS
NTAPI
InitVideo(VOID)
{
    ULONG iDevNum, iVGACompatible = -1, ulMaxObjectNumber = 0;
    WCHAR awcDeviceName[20];
    WCHAR awcBuffer[256];
    NTSTATUS Status;
    PGRAPHICS_DEVICE pGraphicsDevice;
    ULONG cbValue;
    HKEY hkey;

    TRACE("----------------------------- InitVideo() -------------------------------\n");

    /* Open the key for the boot command line */
    Status = RegOpenKey(L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control", &hkey);
    if (NT_SUCCESS(Status))
    {
        cbValue = 256;
        Status = RegQueryValue(hkey, L"SystemStartOptions", REG_SZ, awcBuffer, &cbValue);
        if (NT_SUCCESS(Status))
        {
            /* Check if VGA mode is requested. */
            if (wcsstr(awcBuffer, L"BASEVIDEO") != 0)
            {
                ERR("VGA mode requested.\n");
                gbBaseVideo = TRUE;
            }
        }

        ZwClose(hkey);
    }

    /* Open the key for the adapters */
    Status = RegOpenKey(KEY_VIDEO, &hkey);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not open HARDWARE\\DEVICEMAP\\VIDEO registry key:0x%lx\n", Status);
        return Status;
    }

    /* Read the name of the VGA adapter */
    cbValue = 20;
    Status = RegQueryValue(hkey, L"VgaCompatible", REG_SZ, awcDeviceName, &cbValue);
    if (NT_SUCCESS(Status))
    {
        iVGACompatible = _wtoi(&awcDeviceName[13]);
        ERR("VGA adapter = %lu\n", iVGACompatible);
    }

    /* Get the maximum mumber of adapters */
    if (!RegReadDWORD(hkey, L"MaxObjectNumber", &ulMaxObjectNumber))
    {
        ERR("Could not read MaxObjectNumber, defaulting to 0.\n");
    }

    TRACE("Found %lu devices\n", ulMaxObjectNumber + 1);

    /* Loop through all adapters */
    for (iDevNum = 0; iDevNum <= ulMaxObjectNumber; iDevNum++)
    {
        /* Create the adapter's key name */
        swprintf(awcDeviceName, L"\\Device\\Video%lu", iDevNum);

        /* Read the reg key name */
        cbValue = sizeof(awcBuffer);
        Status = RegQueryValue(hkey, awcDeviceName, REG_SZ, awcBuffer, &cbValue);
        if (!NT_SUCCESS(Status))
        {
            ERR("failed to query the registry path:0x%lx\n", Status);
            continue;
        }

        /* Initialize the driver for this device */
        pGraphicsDevice = InitDisplayDriver(awcDeviceName, awcBuffer);
        if (!pGraphicsDevice) continue;

        /* Check if this is a VGA compatible adapter */
        if (pGraphicsDevice->StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE)
        {
            /* Save this as the VGA adapter */
            if (!gpVgaGraphicsDevice)
                gpVgaGraphicsDevice = pGraphicsDevice;
            TRACE("gpVgaGraphicsDevice = %p\n", gpVgaGraphicsDevice);
        }
        else
        {
            /* Set the first one as primary device */
            if (!gpPrimaryGraphicsDevice)
                gpPrimaryGraphicsDevice = pGraphicsDevice;
            TRACE("gpPrimaryGraphicsDevice = %p\n", gpPrimaryGraphicsDevice);
        }
    }

    /* Close the device map registry key */
    ZwClose(hkey);

    /* Was VGA mode requested? */
    if (gbBaseVideo)
    {
        /* Check if we found a VGA compatible device */
        if (gpVgaGraphicsDevice)
        {
            /* Set the VgaAdapter as primary */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
            // FIXME: DEVMODE
        }
        else
        {
            ERR("Could not find VGA compatible driver. Trying normal.\n");
        }
    }

    /* Check if we had any success */
    if (!gpPrimaryGraphicsDevice)
    {
        /* Check if there is a VGA device we skipped */
        if (gpVgaGraphicsDevice)
        {
            /* There is, use the VGA device */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
        }
        else
        {
            ERR("No usable display driver was found.\n");
            return STATUS_UNSUCCESSFUL;
        }
    }

    InitSysParams();

    return 1;
}
Esempio n. 19
0
// AddDevice, called when an instance of our supported hardware is found
// Returning anything other than NT_SUCCESS here causes the device to fail
// to initialise
NTSTATUS NTAPI FreeBT_AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject)
{
    NTSTATUS			ntStatus;
    PDEVICE_OBJECT		deviceObject;
    PDEVICE_EXTENSION	deviceExtension;
    POWER_STATE			state;
    KIRQL				oldIrql;
	UNICODE_STRING		uniDeviceName;
	WCHAR				wszDeviceName[255]={0};
	UNICODE_STRING		uniDosDeviceName;
	LONG				instanceNumber=0;

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_AddDevice: Entered\n"));

    deviceObject = NULL;

	swprintf(wszDeviceName, L"\\Device\\FbtUsb%02d", instanceNumber);
	RtlInitUnicodeString(&uniDeviceName, wszDeviceName);
	ntStatus=STATUS_OBJECT_NAME_COLLISION;
	while (instanceNumber<99 && !NT_SUCCESS(ntStatus))
	{
		swprintf(wszDeviceName, L"\\Device\\FbtUsb%02d", instanceNumber);
		uniDeviceName.Length = wcslen(wszDeviceName) * sizeof(WCHAR);
		FreeBT_DbgPrint(1, ("FBTUSB: Attempting to create device %ws\n", wszDeviceName));
		ntStatus = IoCreateDevice(
						DriverObject,                   // our driver object
						sizeof(DEVICE_EXTENSION),       // extension size for us
						&uniDeviceName,					// name for this device
						FILE_DEVICE_UNKNOWN,
						0,								// device characteristics
						FALSE,                          // Not exclusive
						&deviceObject);                 // Our device object

		if (!NT_SUCCESS(ntStatus))
			instanceNumber++;

	}

    if (!NT_SUCCESS(ntStatus))
	{
        FreeBT_DbgPrint(1, ("FBTUSB: Failed to create device object\n"));
        return ntStatus;

    }

	FreeBT_DbgPrint(1, ("FBTUSB: Created device %ws\n", wszDeviceName));

    deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension;
    deviceExtension->FunctionalDeviceObject = deviceObject;
    deviceExtension->PhysicalDeviceObject = PhysicalDeviceObject;
    deviceObject->Flags |= DO_DIRECT_IO;

	swprintf(deviceExtension->wszDosDeviceName, L"\\DosDevices\\FbtUsb%02d", instanceNumber);
	RtlInitUnicodeString(&uniDosDeviceName, deviceExtension->wszDosDeviceName);
	ntStatus=IoCreateSymbolicLink(&uniDosDeviceName, &uniDeviceName);
	if (!NT_SUCCESS(ntStatus))
	{
		FreeBT_DbgPrint(1, ("FBTUSB: Failed to create symbolic link %ws to %ws, status=0x%08x\n", deviceExtension->wszDosDeviceName, wszDeviceName, ntStatus));
		IoDeleteDevice(deviceObject);
		return ntStatus;

	}

	FreeBT_DbgPrint(1, ("FBTUSB: Created symbolic link %ws\n", deviceExtension->wszDosDeviceName));

    KeInitializeSpinLock(&deviceExtension->DevStateLock);

    INITIALIZE_PNP_STATE(deviceExtension);

    deviceExtension->OpenHandleCount = 0;

    // Initialize the selective suspend variables
    KeInitializeSpinLock(&deviceExtension->IdleReqStateLock);
    deviceExtension->IdleReqPend = 0;
    deviceExtension->PendingIdleIrp = NULL;

    // Hold requests until the device is started
    deviceExtension->QueueState = HoldRequests;

    // Initialize the queue and the queue spin lock
    InitializeListHead(&deviceExtension->NewRequestsQueue);
    KeInitializeSpinLock(&deviceExtension->QueueLock);

    // Initialize the remove event to not-signaled.
    KeInitializeEvent(&deviceExtension->RemoveEvent, SynchronizationEvent, FALSE);

    // Initialize the stop event to signaled.
    // This event is signaled when the OutstandingIO becomes 1
    KeInitializeEvent(&deviceExtension->StopEvent, SynchronizationEvent, TRUE);

    // OutstandingIo count biased to 1.
    // Transition to 0 during remove device means IO is finished.
    // Transition to 1 means the device can be stopped
    deviceExtension->OutStandingIO = 1;
    KeInitializeSpinLock(&deviceExtension->IOCountLock);

#ifdef ENABLE_WMI 
    // Delegating to WMILIB
    ntStatus = FreeBT_WmiRegistration(deviceExtension);
    if (!NT_SUCCESS(ntStatus))
	{
        FreeBT_DbgPrint(1, ("FBTUSB: FreeBT_WmiRegistration failed with %X\n", ntStatus));
        IoDeleteDevice(deviceObject);
		IoDeleteSymbolicLink(&uniDosDeviceName);
        return ntStatus;

    }
#endif

    // Set the flags as underlying PDO
    if (PhysicalDeviceObject->Flags & DO_POWER_PAGABLE)
	{
        deviceObject->Flags |= DO_POWER_PAGABLE;

    }

    // Typically, the function driver for a device is its
    // power policy owner, although for some devices another
    // driver or system component may assume this role.
    // Set the initial power state of the device, if known, by calling
    // PoSetPowerState.
    deviceExtension->DevPower = PowerDeviceD0;
    deviceExtension->SysPower = PowerSystemWorking;

    state.DeviceState = PowerDeviceD0;
    PoSetPowerState(deviceObject, DevicePowerState, state);

    // attach our driver to device stack
    // The return value of IoAttachDeviceToDeviceStack is the top of the
    // attachment chain.  This is where all the IRPs should be routed.
    deviceExtension->TopOfStackDeviceObject = IoAttachDeviceToDeviceStack(deviceObject, PhysicalDeviceObject);
    if (NULL == deviceExtension->TopOfStackDeviceObject)
	{
#ifdef ENABLE_WMI
        FreeBT_WmiDeRegistration(deviceExtension);
#endif
        IoDeleteDevice(deviceObject);
		IoDeleteSymbolicLink(&uniDosDeviceName);
        return STATUS_NO_SUCH_DEVICE;

    }

    // Register device interfaces
    ntStatus = IoRegisterDeviceInterface(deviceExtension->PhysicalDeviceObject,
                                         &GUID_CLASS_FREEBT_USB,
                                         NULL,
                                         &deviceExtension->InterfaceName);
    if (!NT_SUCCESS(ntStatus))
	{
#ifdef ENABLE_WMI
        FreeBT_WmiDeRegistration(deviceExtension);
#endif
        IoDetachDevice(deviceExtension->TopOfStackDeviceObject);
        IoDeleteDevice(deviceObject);
		IoDeleteSymbolicLink(&uniDosDeviceName);
        return ntStatus;

    }

    if (IoIsWdmVersionAvailable(1, 0x20))
	{
        deviceExtension->WdmVersion = WinXpOrBetter;

    }

    else if (IoIsWdmVersionAvailable(1, 0x10))
	{
        deviceExtension->WdmVersion = Win2kOrBetter;

    }

    else if (IoIsWdmVersionAvailable(1, 0x5))
	{
        deviceExtension->WdmVersion = WinMeOrBetter;

    }

    else if (IoIsWdmVersionAvailable(1, 0x0))
	{
        deviceExtension->WdmVersion = Win98OrBetter;

    }

    deviceExtension->SSRegistryEnable = 0;
    deviceExtension->SSEnable = 0;

    // WinXP only: check the registry flag indicating whether
	// the device should selectively suspend when idle
    if (WinXpOrBetter == deviceExtension->WdmVersion)
	{
        FreeBT_GetRegistryDword(FREEBT_REGISTRY_PARAMETERS_PATH,
                                 L"BulkUsbEnable",
                                 (PULONG)(&deviceExtension->SSRegistryEnable));
        if (deviceExtension->SSRegistryEnable)
		{
            // initialize DPC
            KeInitializeDpc(&deviceExtension->DeferredProcCall, DpcRoutine, deviceObject);

            // initialize the timer.
            // the DPC and the timer in conjunction,
            // monitor the state of the device to
            // selectively suspend the device.
            KeInitializeTimerEx(&deviceExtension->Timer, NotificationTimer);

            // Initialize the NoDpcWorkItemPendingEvent to signaled state.
            // This event is cleared when a Dpc is fired and signaled
            // on completion of the work-item.
            KeInitializeEvent(&deviceExtension->NoDpcWorkItemPendingEvent, NotificationEvent, TRUE);

            // Initialize the NoIdleReqPendEvent to ensure that the idle request
            // is indeed complete before we unload the drivers.
            KeInitializeEvent(&deviceExtension->NoIdleReqPendEvent, NotificationEvent, TRUE);

        }

    }

    // Initialize the NoIdleReqPendEvent to ensure that the idle request
    // is indeed complete before we unload the drivers.
    KeInitializeEvent(&deviceExtension->DelayEvent, NotificationEvent, FALSE);

    // Clear the DO_DEVICE_INITIALIZING flag.
    // Note: Do not clear this flag until the driver has set the
    // device power state and the power DO flags.
    deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
    InterlockedIncrement(&instanceNumber);

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_AddDevice: Leaving\n"));

    return ntStatus;

}
Esempio n. 20
0
VOID
GetVersionInfo(
    BOOL Verbose
    )
{
    WCHAR          NameBuffer[MAXVERSIONBUFFER];
    WCHAR          Title1[128];
    WCHAR          Title2[128];
    WCHAR          wszPID[MAXVERSIONSTRING];
    WCHAR          wszPro[MAXVERSIONSTRING];
    WCHAR          wszSrv[MAXVERSIONSTRING];
    WCHAR          wszPBuild[MAXVERSIONSTRING];
    WCHAR          wszEvaluation[MAXVERSIONSTRING];
    UNICODE_STRING UserBuildString;
    UNICODE_STRING UserTypeString;
    UNICODE_STRING UserCSDString;
    NTSTATUS       Status;


    RTL_QUERY_REGISTRY_TABLE BaseServerRegistryConfigurationTable[] = {

        {NULL,
         RTL_QUERY_REGISTRY_DIRECT,
         L"CurrentBuildNumber",
         &UserBuildString,
         REG_NONE,
         NULL,
         0},

        {NULL,
         RTL_QUERY_REGISTRY_DIRECT,
         L"CurrentType",
         &UserTypeString,
         REG_NONE,
         NULL,
         0},

        {NULL,
         RTL_QUERY_REGISTRY_DIRECT,
         L"CSDVersion",
         &UserCSDString,
         REG_NONE,
         NULL,
         0},

        {NULL,
         0,
         NULL,
         NULL,
         REG_NONE,
         NULL,
         0}
    };

    UserBuildString.Buffer          = &NameBuffer[OFFSET_BLDSTRING];
    UserBuildString.Length          = 0;
    UserBuildString.MaximumLength   = MAXVERSIONSTRING * sizeof(WCHAR);

    UserTypeString.Buffer           = &NameBuffer[OFFSET_TYPSTRING];
    UserTypeString.Length           = 0;
    UserTypeString.MaximumLength    = MAXVERSIONSTRING * sizeof(WCHAR);

    UserCSDString.Buffer            = &NameBuffer[OFFSET_CSDSTRING];
    UserCSDString.Length            = 0;
    UserCSDString.MaximumLength     = MAXVERSIONSTRING * sizeof(WCHAR);

    Status = RtlQueryRegistryValues(RTL_REGISTRY_WINDOWS_NT,
                                    L"",
                                    BaseServerRegistryConfigurationTable,
                                    NULL,
                                    NULL);

    if (!NT_SUCCESS(Status)) {
        RIPMSG1(RIP_WARNING, "GetVersionInfo failed with status %x", Status);
        return;
    }

    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTID, wszPID, ARRAY_SIZE(wszPID) );
    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTPRO, wszPro, ARRAY_SIZE(wszPro) );
    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTSRV, wszSrv, ARRAY_SIZE(wszSrv) );
    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTBUILD, wszPBuild, ARRAY_SIZE(wszPBuild) );

    /*
     * Write out Debugging Version message.
     */

    /*
     * Bug 280256 - joejo
     * Create new desktop build information strings
     */
    swprintf(
        wszProductName,
        wszPID,
        ((USER_SHARED_DATA->NtProductType == NtProductWinNt) ? wszPro : wszSrv)
        );

    
    if (gfUnsignedDrivers) {
        /* This takes precedence */
        ServerLoadString( hModuleWin, STR_TESTINGONLY, wszEvaluation, ARRAY_SIZE(wszEvaluation) );
    } else if (USER_SHARED_DATA->SystemExpirationDate.QuadPart) {
        ServerLoadString(hModuleWin, STR_DTBS_EVALUATION, wszEvaluation,
                ARRAY_SIZE(wszEvaluation));
    } else {
        wszEvaluation[0] = '\0';
    }

    swprintf(
        wszProductBuild,
        wszPBuild,
        wszEvaluation,
        UserBuildString.Buffer
        );

    if (Verbose) {

        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE1, Title1, ARRAY_SIZE(Title1) );
        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE2, Title2, ARRAY_SIZE(Title2) );

        swprintf(
            wszT,
            UserCSDString.Length == 0 ? Title1 : Title2,
            UserBuildString.Buffer,
            UserCSDString.Buffer,
            USER_SHARED_DATA->NtSystemRoot
            );

    } else {
        PWSTR s = wcsrchr( UserTypeString.Buffer, L' ' );
        if (s) {
            s += 1;
        } else {
            s = UserTypeString.Buffer;
        }

        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE3, Title1, ARRAY_SIZE(Title1) );
        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE4, Title2, ARRAY_SIZE(Title2) );

        swprintf(
            wszT,
            UserCSDString.Length == 0 ? Title1 : Title2,
            UserBuildString.Buffer,
            UserCSDString.Buffer,
            s
            );
    }
}
Esempio n. 21
0
void ExhTestCPEngine::ExhTestProperties()
{
	HRESULT hr;

	// REVIEW LarsH: how do we pass in the location of the UnicodeData.txt file as
	// a parameter?  Env var?
	StrAnsi staDataFile = L"d:\\lars\\Unicode\\UnicodeData.txt";
	FILE *pFileIn = fopen(staDataFile, "r");
	if (!pFileIn)
		FailureFormat("Unable to open Unicode data file %s", staDataFile);

	CodePtData cpdCurrent, cpdNext;
	cpdNext.chCodeValue = -1;	// uninitialized

	// TODO LarsH: We should test through 0x10FFFF, but currently there are
	// some problems with higher characters which have been postponed,
	// so in order to avoid a humungous error log we'll stick with the first page for now.
	// Raid #31
#define JUST_FIRST_PAGE
#ifdef JUST_FIRST_PAGE
	for (int ch = 0; ch <= 0xFFFF; ch++)
#else
	for (int ch = 0; ch <= 0x10FFFF; ch++)
#endif
	{
		if (! (ch % 0x1000))
			LogFormat("%x:\n", ch);

		// Read in the next record unless we've already got this data
		if (cpdNext.chCodeValue < ch)
			ParseRecord(pFileIn, &cpdNext);
		// This is NOT an "else"; it may happen in addition to the above.
		if (cpdNext.chCodeValue == ch)
		{
			// got the right record; copy it over
			cpdCurrent.chCodeValue = ch;
			strcpy(cpdCurrent.szCategory, cpdNext.szCategory);
			wcscpy(cpdCurrent.szwName, cpdNext.szwName);
			cpdCurrent.nNumericValue = cpdNext.nNumericValue;
			cpdCurrent.nCombiningClass = cpdNext.nCombiningClass;
			wcscpy(cpdCurrent.szwDecomposition, cpdNext.szwDecomposition);
			cpdCurrent.chUpper = cpdNext.chUpper;
			cpdCurrent.chLower = cpdNext.chLower;
			cpdCurrent.chTitle = cpdNext.chTitle;
		}

		// Treat special ranges specially:
		if (ch >= 0x3400 && ch <= 0x4db5 || ch >= 0x4e00 && ch <= 0x9fa5)
		{
			// CJK Ideographs (Extension A and other)
			// Most data is same as previous, so don't need to load;
			// but must set names algorithmically.
			swprintf(cpdCurrent.szwName, L"CJK UNIFIED IDEOGRAPH-%X", ch);
		}
		else if (ch >= 0xac00 && ch <= 0xd7a3)
		{
			// Hangul Syllables
			// Data for 0xAC00 is loaded, and applies to all others, except
			//  name and decomp.
			HangulDecomposition(ch, cpdCurrent.szwDecomposition);
			HangulName(cpdCurrent.szwDecomposition, cpdCurrent.szwName);
		}
		else if (ch >= 0xd800 &&
			  // ch <= 0xdb7f || ch >= 0xdb80 && ch <= 0xdbff ||
			  // ch >= 0xdc00 && ch <= 0xdfff || ch >= 0xe000
				 ch <= 0xf8ff)
		{
			// Consecutive ranges: Non-Private Use High Surrogates,
			// Private Use High Surrogates, Low Surrogates, Private Use Area.
			// All of these are nameless (UnicodeData File Format v3.0.0)
			// TODO LarsH: change all this before closing Raid #24.
			cpdCurrent.szwName[0] = '\0';
		}
		else if (ch == 0xfffe || ch == 0xffff ||  // explicitly "not Unicode chars"
			cpdNext.chCodeValue > ch || (cpdNext.chCodeValue < ch && feof(pFileIn)))
		{
			// Not assigned in the data file.
			cpdCurrent.chCodeValue = ch;
			cpdCurrent.szwName[0] = '\0';
			strcpy(cpdCurrent.szCategory, "Cn");
			cpdCurrent.nCombiningClass = 0;
			// Must distinguish between lack of a NumericValue and a zero NumericValue.
			cpdCurrent.nNumericValue = -1;
			cpdCurrent.szwDecomposition[0] = '\0';
			// Zero is not an anycase equivalent of any character.
			cpdCurrent.chLower = cpdCurrent.chUpper = cpdCurrent.chTitle = ch;
		}

		// ** If looking for a character with a specific combination of properties,
		// ** you can test it here.  This would be better done in SQL.
		//	if (cpdCurrent.szCategory[0] != 'L' && cpdCurrent.chUpper > 0)
		//		LogFormat("*** U+%x fulfills conditions\n");
		//	continue; // skip all the usual tests if desired

		// Make sure the property interface methods get the same data.
		LgGeneralCharCategory cc = ParseCC(cpdCurrent.szCategory);
		CheckCat(ch, cc);

		ComBool fLet, fPun, fNum, fSep, fSym, fMar, fOth, fAll;
#define CheckBoolProp(prop, var, index, letter) \
		{ \
			hr = m_qpropeng->get_##prop(ch, &var); \
			WarnHr(hr); \
			if (var != (cpdCurrent.szCategory[index] == letter)) \
				FailureFormat("get_" #prop "(U+%x) gave wrong answer", ch); \
		}

		CheckBoolProp(IsLetter,      fLet, 0, 'L');
		CheckBoolProp(IsPunctuation, fPun, 0, 'P');
		CheckBoolProp(IsNumber,      fNum, 0, 'N');
		CheckBoolProp(IsSeparator,   fSep, 0, 'Z');
		CheckBoolProp(IsSymbol,      fSym, 0, 'S');
		CheckBoolProp(IsMark,        fMar, 0, 'M');
		CheckBoolProp(IsOther,       fOth, 0, 'C');

		// REVIEW LarsH: is int(ComBool) guaranteed to be 1 if true?  I think so.
		int nCat;
		if ((nCat = fLet + fPun + fNum + fSep + fSym + fMar + fOth) != 1)
			FailureFormat("Codepoint U+%x is in %d categories instead of one.",
				ch, nCat);

		if (fLet)
		{
			ComBool fUpp, fLow, fTit, fMod, fOth;
			CheckBoolProp(IsUpper,    fUpp, 1, 'u');
			CheckBoolProp(IsLower,    fLow, 1, 'l');
			CheckBoolProp(IsTitle,    fTit, 1, 't');
			CheckBoolProp(IsModifier, fMod, 1, 'm');
			CheckBoolProp(IsOtherLetter,    fOth, 1, 'o');
			if ((nCat = fUpp + fLow + fTit + fMod + fOth) != 1)
				FailureFormat("Letter U+%x is in %d subcategories instead of one.",
					ch, nCat);
		}
		else
		{
			// All should be false.
			CheckBoolProp(IsUpper,    fAll, 0, 'L');
			CheckBoolProp(IsLower,    fAll, 0, 'L');
			CheckBoolProp(IsTitle,    fAll, 0, 'L');
			CheckBoolProp(IsModifier, fAll, 0, 'L');
			CheckBoolProp(IsOtherLetter, fAll, 0, 'L');
		}

		if (fPun)
		{
			ComBool fOpe, fClo, fMed;
			CheckBoolProp(IsOpen,       fOpe, 1, 's');
			CheckBoolProp(IsClose,      fOpe, 1, 'e');
			CheckBoolProp(IsWordMedial, fOpe, 1, 'c');
			// TODO LarsH: update this if definition in Language.idh changes, e.g.
			// if the above methods come to be true for Pd, Pi, Pf
		}
		else
		{
			CheckBoolProp(IsOpen,       fAll, 0, 'P');
			CheckBoolProp(IsClose,      fAll, 0, 'P');
			CheckBoolProp(IsWordMedial, fAll, 0, 'P');
		}

		// IsControl should return true if category is Cc, false otherwise:
		CheckBoolProp(IsControl, fAll, 1, (cpdCurrent.szCategory[0] == 'C' ? 'c' : 0));

#undef CheckBoolProp

#define IsLetter() (cpdCurrent.szCategory[0] == 'L')
#define IsUpper() (cpdCurrent.szCategory[1] == 'u')
#define IsLower() (cpdCurrent.szCategory[1] == 'l')
#define IsTitle() (cpdCurrent.szCategory[1] == 't')
		// We must check IsLetter() etc. because the docs say, if it's not Lu/Ll/Tt, ToUpper() etc.
		// don't do case conversion, even if the Unicode database gives a conversion.

		int chUpper = -1, chLower = -1, chTitle = -1;

		// TODO LarsH: some of these should check different locales
		// if such data exists in SpecialCasing.txt

		hr = m_qpropeng->get_ToUpperCh(ch, &chUpper);
		if (FAILED(hr))
			FailureFormat("get_ToUpperCh(0x%x) gave result %s", ch, AsciiHresult(hr));
		int chUExp = (IsLetter() && (IsLower() || IsTitle()) && cpdCurrent.chUpper) ?
			cpdCurrent.chUpper : ch;
		if (chUpper != chUExp)
		{
			FailureFormat("get_ToUpperCh(0x%x {%s}) returned 0x%x instead of 0x%x",
				ch, cpdCurrent.szCategory, chUpper, chUExp);
		}

		hr = m_qpropeng->get_ToLowerCh(ch, &chLower);
		if (FAILED(hr))
			FailureFormat("get_ToLowerCh(0x%x) gave result %s", ch, AsciiHresult(hr));
		int chLExp = (IsLetter() && (IsUpper() || IsTitle()) && cpdCurrent.chLower) ?
			cpdCurrent.chLower : ch;
		if (chLower != chLExp)
		{
			FailureFormat("get_ToLowerCh(0x%x {%s}) returned 0x%x instead of 0x%x",
				ch, cpdCurrent.szCategory, chLower, chLExp);
		}
		hr = m_qpropeng->get_ToTitleCh(ch, &chTitle);
		if (FAILED(hr))
			FailureFormat("get_ToTitleCh(0x%x) gave result %s", ch, AsciiHresult(hr));
#define FIXED_BUG_198 // just for now
#ifdef FIXED_BUG_198
		int chTExp = (IsLetter() && (IsUpper() || IsLower())) ?
			(cpdCurrent.chTitle ? cpdCurrent.chTitle : cpdCurrent.chUpper ? cpdCurrent.chUpper : ch) :
			ch;
		// ToTitleCh() returns the uppercase if there is no titlecase value defined

		if (chTitle != chTExp)
		{
			FailureFormat("get_ToTitleCh(0x%x {%s}) returned 0x%x instead of 0x%x",
				ch, cpdCurrent.szCategory, chTitle, chTExp);
		}
#endif // FIXED_BUG_198

		// TODO LarsH: test get_ToLower, etc. (BSTR functions)
		// These should take into account any special casing (SpecialCasing.txt), by testing
		// different locales (esp. Turkish) and contexts (FINAL/NON_FINAL, MODERN/NON_MODERN).
		wchar pwz[2];
		pwz[0] = (wchar)ch;
		pwz[1] = '\0';
		SmartBstr sbstrFrom(pwz), sbstrTo = L"fish";

		// This one properly gives a warning if ch is half of a surrogate pair.
		if (ch >= 0xd800 && ch <= 0xdfff) // half a surrogate pair
		{
			IgnoreWarnings iw;
			hr = m_qpropeng->ToLower(sbstrFrom, &sbstrTo);
			TestFailZero(sbstrTo, "ToLower");
			if (SUCCEEDED(hr))
				FailureFormat("ToLower with 0x%x (half a surrogate pair) should have failed", ch);
		}
		else
		{
			hr = m_qpropeng->ToLower(sbstrFrom, &sbstrTo);
			TestFailZero(sbstrTo, "ToLower");
			WarnHr(hr);
			// TODO LarsH: check that the return value from get_ToLower is correct
			// TODO LarsH: use smart bstrs where possible
		}


		// TODO LarsH: test get_ToLowerRgch, etc. (Rgch functions)

		// TODO LarsH: test IsUserDefinedClass().  Right now there is no way to define
		// classes, so this will always return false.
		ComBool fRet;
		hr = m_qpropeng->get_IsUserDefinedClass(ch, 'A', &fRet);
		WarnHr(hr);
		if (fRet)
			FailureFormat("Character U+%x is a member of class 'A'??", ch);

		// TODO LarsH: test SoundAlikeKey

		// REVIEW LarsH: is this bstr causing a memory leak on every iteration of ch?
		SmartBstr sbstr = L"foo";

		// TODO LarsH: Remove this kludge once get_CharacterName(Hangul) is working.
		if (ch >= 0xac00 && ch <= 0xd7a3)
			goto skipHangul;

		hr = m_qpropeng->get_CharacterName(ch, &sbstr);
		TestFailZero(sbstr, "get_CharacterName");
		if (FAILED(hr))
			FailureFormat("get_CharacterName(U+%x) failed", ch);
		else if (
#ifndef FIXED_BUG_24
			!(ch >= 0xd800 && ch <= 0xf8ff) &&
#endif
				wcscmp(cpdCurrent.szwName, sbstr))
		{
			FailureFormat(L"get_CharacterName(U+%x) returned \"%s\" instead of \"%s\".",
				ch, sbstr, cpdCurrent.szwName);
		}
		// if (sbstr)
		//  	SysFreeString(sbstr);

#ifdef FIXED_BUG_125
		sbstr = L"foo";
		hr = m_qpropeng->get_Decomposition(ch, &sbstr);
		TestFailZero(sbstr, "get_Decomposition");
		if (FAILED(hr))
			FailureFormat("get_Decomposition(U+%x) failed", ch);
		// REVIEW LarsH: Does wcscmp understand NULL sbstrs?  Apparently...
		else if (sbstr ? wcscmp(cpdCurrent.szwDecomposition, sbstr) :
				cpdCurrent.szwDecomposition[0])
		{
			FailureFormat("Got wrong decomposition for U+%x", ch);
		}
		// if (sbstr)
		// 	SysFreeString(bstr);
#endif // FIXED_BUG_125

		sbstr = NULL;

		// TODO LarsH: test DecompositionRgch
		// That will probably require a separate pass through the whole UnicodeData
		// file to build up a hash table or sthg...



skipHangul:

		int nNumericValue;
		{
			IgnoreWarnings iw;
			hr = m_qpropeng->get_NumericValue(ch, &nNumericValue);
		}
		if (fNum && (cc == kccNd || cc == kccNl || cc == kccNo) && cpdCurrent.nNumericValue > -1)
		{
			if (FAILED(hr))
				FailureFormat("get_NumericValue(U+%x) failed with hr=%s", ch, AsciiHresult(hr));
			else if (nNumericValue != cpdCurrent.nNumericValue)
			{
				FailureFormat("get_NumericValue(U+%x) returned %d instead of %d",
					ch, nNumericValue, cpdCurrent.nNumericValue);
			}
		}
		else if (hr != E_UNEXPECTED)
		{
			FailureFormat("get_NumericValue(U+%x {%s}) gave result %s instead of E_UNEXPECTED",
				ch, cpdCurrent.szCategory, AsciiHresult(hr));
		}

#define FIXED_BUG_18 1  // Seems to be fixed now.
#ifdef FIXED_BUG_18
		int nCombClass;
		hr = m_qpropeng->get_CombiningClass(ch, &nCombClass);
		WarnHr(hr);
		if (nCombClass != cpdCurrent.nCombiningClass)
		{
			FailureFormat("get_CombiningClass(U+%x) gave %d instead of %d",
				ch, nCombClass, cpdCurrent.nCombiningClass);
		}
#endif
		// TODO LarsH: test everything else


		// TODO LarsH: test get_Comment

		// TODO LarsH: test GetLineBreakProps if not obsolete
		// TODO LarsH: test GetLineBreakStatus if not obsolete

	}
}
Esempio n. 22
0
//---------------------------------------------------------------------------------------------
// Name:
// Desc:
//---------------------------------------------------------------------------------------------
HRESULT CManipulator::SaveConfig(wchar_t* file)
{
	int i;
	wchar_t string[512];
	wchar_t name[512];
	int pid;
	cprimitive* parent;


	

	FILE* file2 = _wfopen(file,L"w+");
	if(file2 == NULL) MessageBox(0,0,0,0);
	fclose(file2);

	//chains
	swprintf(string, L"%d", numOfChains);
	IniWrite(file,L"manipulator",L"chainsize",string);


	for(i=0; i < numOfChains; i++)
	{
		swprintf(name, L"chain_%d", i);

		//coefficient
		swprintf(string, L"%.2f", cube[i]->fCoefficient);
		IniWrite(file, name, L"coefficient", string);

		//direction
		swprintf(string, L"%.2f", cube[i]->fDirection);
		IniWrite(file, name, L"direction", string);

		//displace
		swprintf(string, L"%.2f", cube[i]->fDisplace);
		IniWrite(file, name, L"displace", string);

		//length
		swprintf(string, L"%.2f", cube[i]->fLength);
		IniWrite(file, name, L"length", string);

		//width
		swprintf(string, L"%.2f", cube[i]->fWidth);
		IniWrite(file, name, L"width", string);

		//initangle
		swprintf(string, L"%.2f %.2f", (float)cube[i]->vAngle.x, (float)cube[i]->vAngle.y);
		IniWrite(file, name, L"initangle", string);

		//angle_restrict_phi
		swprintf(string, L"%.2f %.2f", cube[i]->restrictAngleX.x, cube[i]->restrictAngleX.y);
		IniWrite(file, name, L"angle_restrict_phi", string);

		//angle_restrict_theta
		swprintf(string, L"%.2f %.2f", cube[i]->restrictAngleY.x, cube[i]->restrictAngleY.y);
		IniWrite(file, name, L"angle_restrict_theta", string);

		//offset
		swprintf(string, L"%.2f %.2f %.2f", cube[i]->vOffset.x, cube[i]->vOffset.y, cube[i]->vOffset.z);
		IniWrite(file, name, L"offset", string);

		//mass
		swprintf(string, L"%.2f", cube[i]->fMass);
		IniWrite(file, name, L"mass", string);

		//booleans
		IniWrite(file, name, L"tilt", (cube[i]->bTilt ? L"1" : L"0"));
		IniWrite(file, name, L"pressure", (cube[i]->bPressure ? L"1" : L"0"));
		IniWrite(file, name, L"laser", (cube[i]->bLaser ? L"1" : L"0"));

		//parent_index
		parent = GetParent(cube[i],cube[0]);
		if(parent == NULL) pid = -1;
		else pid = parent->id;

		swprintf(string,L"%d",pid);
		IniWrite(file, name, L"parent_index", string);

		IniWrite(file, name, L"model", L"");

		
	}

	//limbs
	swprintf(string, L"%d", limbs.size());
	IniWrite(file,L"limbs",L"num",string);

	for(i=0; i<limbs.size();i++)
	{
		swprintf(name, L"limb_%d", i);
		IniWrite(file,name,L"name",limbs[i]->name);

		swprintf(string, L"%d", limbs[i]->firstchain);
		IniWrite(file,name,L"first",string);

		swprintf(string, L"%d", limbs[i]->lastchain);
		IniWrite(file,name,L"last",string);
	}


	//-------

	MessageBox(0,L"Конфигурация успешно сохранена!", L"Сохранение", 0);

	return S_OK;
}
DWORD TcpIpReader::startServer() {
	breakSocket=false;

	wchar_t log[300];
	while (true) {
		//__try {
			fd_set readfds;

			FD_ZERO(&readfds);
			// Set server socket to set
			FD_SET(socket, &readfds);

			// Timeout parameter
			timeval tv = { 0 };
			tv.tv_sec = 5;

			while(true) {
				if (breakSocket)
					return 0;
				FD_SET(socket, &readfds);
				int ret = select(0, &readfds, NULL, NULL, &tv);
				if (ret > 0)
					break;
				if (ret<0) {
					wchar_t log[100];
					DWORD err=WSAGetLastError();
					swprintf(log,L"[BixVReader]wsa err:%x",err);
					OutputDebugString(log);
					if (err==0x2736) {
						socket=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,0);
						sockaddr_in Service;
						Service.sin_family = AF_INET;
						Service.sin_addr.s_addr = inet_addr("127.0.0.1");
						Service.sin_port = htons((u_short)(port));
						bind(socket, (SOCKADDR *) &Service, sizeof (Service));
						listen(socket, 1);

						FD_ZERO(&readfds);
						// Set server socket to set
						FD_SET(socket, &readfds);
					}
				}
			}

			SOCKET AcceptEventSocket;

			AcceptSocket = accept(socket, NULL, NULL);
			closesocket(socket);
			socket=NULL;
			if (AcceptSocket == INVALID_SOCKET)
				return 0;

			swprintf(log,L"[BixVReader]Socket connected:%i",AcceptSocket);
			OutputDebugString(log);

			FD_ZERO(&readfds);
			// Set server socket to set
			FD_SET(eventsocket, &readfds);

			while(true) {
				if (breakSocket)
					return 0;
				FD_SET(eventsocket, &readfds);
				int ret = select(0, &readfds, NULL, NULL, &tv);
				if (ret > 0)
					break;
				if (ret<0) {
					DWORD err=WSAGetLastError();
					swprintf(log,L"[BixVReader]wsa err:%x",err);
					OutputDebugString(log);
					if (err==0x2736) {
						eventsocket=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,0);
						sockaddr_in eventService;
						eventService.sin_family = AF_INET;
						eventService.sin_addr.s_addr = inet_addr("127.0.0.1");
						eventService.sin_port = htons((u_short)(eventPort));
						bind(eventsocket, (SOCKADDR *) &eventService, sizeof (eventService));
						listen(eventsocket, 1);

						FD_ZERO(&readfds);
						// Set server socket to set
						FD_SET(eventsocket, &readfds);
					}
				}
			}

			AcceptEventSocket = accept(eventsocket, NULL, NULL);
			closesocket(eventsocket);
			eventsocket=NULL;
			if (AcceptEventSocket == INVALID_SOCKET)
				return 0;

			swprintf(log,L"[BixVReader]Event Socket connected:%i",AcceptEventSocket);
			OutputDebugString(log);

			if (waitInsertIpr!=NULL) {
				// if I'm waiting for card insertion, verify if there's a card present
				if (initProtocols()) {
					SectionLocker lock(device->m_RequestLock);
					if (waitInsertIpr->UnmarkCancelable()==S_OK)
						waitInsertIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
					waitInsertIpr=NULL;
					state=SCARD_SWALLOWED;
				}
			}
			
			while (true) {
				// wait for a command
				DWORD command=0;
				int read=0;
				if ((read=recv(AcceptEventSocket,(char*)&command,sizeof(DWORD),MSG_WAITALL))<=0) {
					state=SCARD_ABSENT;
					OutputDebugString(L"[BixVReader]Socket error");
					powered=0;
					::shutdown(AcceptSocket,SD_BOTH);
					::shutdown(AcceptEventSocket,SD_BOTH);
					if (waitRemoveIpr!=NULL) {// card inserted
						OutputDebugString(L"[BixVReader]complete Wait Remove");
						SectionLocker lock(device->m_RequestLock);
						if (waitRemoveIpr->UnmarkCancelable()==S_OK) {
							OutputDebugString(L"[BixVReader]Wait Remove Unmarked");
							waitRemoveIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
							OutputDebugString(L"[BixVReader]Wait Remove Completed");
						}
						waitRemoveIpr=NULL;
					}
					if (waitInsertIpr!=NULL) {// card removed
						OutputDebugString(L"[BixVReader]cancel Wait Remove");
						SectionLocker lock(device->m_RequestLock);
						if (waitInsertIpr->UnmarkCancelable()==S_OK) {
							OutputDebugString(L"[BixVReader]Wait Insert Unmarked");
							waitInsertIpr->CompleteWithInformation(HRESULT_FROM_WIN32(ERROR_CANCELLED), 0);
							OutputDebugString(L"[BixVReader]Wait Insert Cancelled");
						}
						waitInsertIpr=NULL;
					}
					break;
				}
				OutputDebugString(L"[BixVReader]Socket data");
				if (command==0)
					powered=0;
				if (command==0 && waitRemoveIpr!=NULL) {// card removed
					SectionLocker lock(device->m_RequestLock);
					state=SCARD_ABSENT;
					if (waitRemoveIpr->UnmarkCancelable()==S_OK)						
						waitRemoveIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
					waitRemoveIpr=NULL;
				}
				else if (command==1 && waitInsertIpr!=NULL) {// card inserted
					SectionLocker lock(device->m_RequestLock);
					state=SCARD_SWALLOWED;
					initProtocols();					
					if (waitInsertIpr->UnmarkCancelable()==S_OK)
						waitInsertIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
					waitInsertIpr=NULL;
				}
			}
		//}
		//__except(EXCEPTION_EXECUTE_HANDLER) {
		//	wchar_t log[300];
		//	DWORD err=GetExceptionCode();
		//	swprintf(log,L"Exception:%08X",err);
		//	OutputDebugString(log);
		//}
	}
	OutputDebugString(L"[BixVReader]Socket quit!!!");
	return 0;
}
Esempio n. 24
0
void log_debug(wchar_t *mess){
  wchar_t *buff=malloc((wcslen(mess)+100)*sizeof(wchar_t));
  swprintf(buff,wcslen(mess)+100,L"DEBUG! %s",mess);
  log_info(buff);
  free(buff);
}
Esempio n. 25
0
// DlgProcOpts(): Dialog Callback
// hwndDlg: hWnd to options dialog
// msg: Window message received
// wParam: Depending on msg
// lParam: Depending on msg
static BOOL CALLBACK DlgProcOptsAcc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	CNetwork* network=(CNetwork*)GetWindowLong(GetParent(hwndDlg),GWL_USERDATA);

	switch (msg)
	{
		case WM_INITDIALOG:	// Options dialog is being initialized
		{
			DBVARIANT dbv;
			HWND hControl;
			char** pszServers=servers;
			TranslateDialogDefault(hwndDlg);

			// Add server to list
			hControl=GetDlgItem(hwndDlg,IDC_SERVER);
			while (*pszServers) {
				ADD_LIST_ITEM(*pszServers);
				pszServers++;
			}

			SendDlgItemMessage(hwndDlg,IDC_AVATARTYPE,CB_ADDSTRING,NULL,(LPARAM)TranslateT("Head Image and User Head"));
			SendDlgItemMessage(hwndDlg,IDC_AVATARTYPE,CB_ADDSTRING,NULL,(LPARAM)TranslateT("Head Image"));
			SendDlgItemMessage(hwndDlg,IDC_AVATARTYPE,CB_ADDSTRING,NULL,(LPARAM)TranslateT("QQ Show"));
			SendDlgItemMessage(hwndDlg,IDC_AVATARTYPE,CB_ADDSTRING,NULL,(LPARAM)TranslateT("None"));

			SendDlgItemMessage(hwndDlg,IDC_CONVERSION,CB_ADDSTRING,NULL,(LPARAM)TranslateT("No Message Conversion"));
			SendDlgItemMessage(hwndDlg,IDC_CONVERSION,CB_ADDSTRING,NULL,(LPARAM)TranslateT("Receive: No Change, Send: Convert to Simplified"));
			SendDlgItemMessage(hwndDlg,IDC_CONVERSION,CB_ADDSTRING,NULL,(LPARAM)TranslateT("Receive: Convert to Traditional, Send: No Change"));
			SendDlgItemMessage(hwndDlg,IDC_CONVERSION,CB_ADDSTRING,NULL,(LPARAM)TranslateT("Receive: Convert to Traditional, Send: Convert to Simplified"));

			if (!(hControl=GetDlgItem(hwndDlg,IDC_NOTICE))) itoa(1,(LPSTR)hControl,10);
			SetWindowText(hControl,L"Miranda IM 专用的 QQ 插件 (MirandaQQ)\n版权所有(C) 2008 小熊工作室,保留所有权利。\n此插件使用 libeva QQ 库,版权所有(C) 云帆。\nThe QQ icon is from Cristal Icons pack, courtesy of Angeli-Ka. Used with permission from author.\n\n此插件是根据 GPL 第二版的条款而授权。你可以修改并重新发布基于此产品的成果,但你「必须保留所有原有的版权宣告」,并将有关之所有代码公开。若要更多信息,请参照 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html 上的 GPL 合约条款,或 http://docs.huihoo.com/open_source/GPL-chinese.html 参考该条款的中文译本。\n最后,由于太多人滥用桥接功能 (桥接20个群过分么?),所以此功能将被永久移除。你们要加回去请自便,但不要再在支持群里询问有关问题。");
			ShowWindow(hControl,SW_SHOWNORMAL);

			if (network) {
				SendMessage(GetDlgItem(hwndDlg,IDC_CONVERSION),CB_SETCURSEL,DBGetContactSettingByte(NULL,network->m_szModuleName,QQ_MESSAGECONVERSION,0),0);

				if(!DBGetContactSetting(NULL,network->m_szModuleName,QQ_LOGINSERVER2,&dbv)) {
					SetDlgItemTextA(hwndDlg,IDC_SERVER,dbv.pszVal);
					DBFreeVariant(&dbv);
				} else {
					SetDlgItemTextA(hwndDlg,IDC_SERVER,*servers);
				}

				// Login ID and Password
				if(!DBGetContactSetting(NULL,network->m_szModuleName,UNIQUEIDSETTING,&dbv)){
					char szID[16];
					ultoa(dbv.lVal,szID,10);
					SetDlgItemTextA(hwndDlg,IDC_LOGIN,szID);
					DBFreeVariant(&dbv);
				}

				SetDlgItemTextA(hwndDlg,IDC_PASSWORD,PASSWORDMASK);

				CHECK_CONTROL(IDC_FORCEINVISIBLE,QQ_INVISIBLE);
				//CHECK_CONTROL(IDC_FORCEUNICODE,QQ_FORCEUNICODE);
				CheckDlgButton(hwndDlg,IDC_FORCEUNICODE,BST_CHECKED);
				EnableWindow(GetDlgItem(hwndDlg,IDC_FORCEUNICODE),FALSE);
				//CHECK_CONTROL2(IDC_AUTOSERVER,QQ_NOAUTOSERVER);
				ShowWindow(GetDlgItem(hwndDlg,IDC_AUTOSERVER),SW_HIDE);

				// Version and Connection Information
				/*
				pszTemp=mir_strdup(szCheckoutTime);

				SetDlgItemTextA(hwndDlg,IDC_VERSION,pszTemp);
				mir_free(pszTemp);
				*/

				WCHAR szTemp[MAX_PATH];
				swprintf(szTemp,TranslateT("This copy of MirandaQQ is based on EVA %S, Module: %S"),version,network->m_szModuleName);
				SetDlgItemText(hwndDlg,IDC_VERSION,szTemp);

				//if (qqSettings->unicode)
					SetDlgItemText(hwndDlg,IDC_UNICODEMSG,TranslateT("Unicode Messaging Support(UTF-8) is Enabled."));
				/*else
					SetDlgItemText(hwndDlg,IDC_UNICODEMSG,TranslateT("Unicode Messaging Support is Disabled."));*/
			}
			return TRUE;
		}


		case WM_COMMAND:	// When a control is toggled
			switch (LOWORD(wParam)) {
				case IDC_LOGIN:
				case IDC_PASSWORD:
				//case IDC_SERVER:
				case IDC_VERSION:
					if (HIWORD(wParam) != EN_CHANGE || (HWND)lParam != GetFocus()) return 0;
					break;
				case IDC_CONVERSION:
				case IDC_SERVER:
					if (HIWORD(wParam) != CBN_SELCHANGE) return 0;
					
			}
			SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
			break;
		
		case WM_NOTIFY:		// When a notify is sent by Options Dialog (Property Sheet)
			if (network && ((LPNMHDR)lParam)->code==PSN_APPLY) {
				int reconnectRequired=0;
				char str[128];
				char login[128];
				DBVARIANT dbv;

				// Login Information
				GetDlgItemTextA(hwndDlg,IDC_LOGIN,login,sizeof(login));
				dbv.pszVal=NULL;
				dbv.lVal=0;
				if(DBGetContactSetting(NULL,network->m_szModuleName,UNIQUEIDSETTING,&dbv) || strtoul(login,NULL,10)!=dbv.dVal)
					reconnectRequired=1;
				
				if(dbv.lVal!=0) DBFreeVariant(&dbv);
				DBWriteContactSettingDword(NULL,network->m_szModuleName,UNIQUEIDSETTING,strtoul(login,NULL,10));
				
				GetDlgItemTextA(hwndDlg,IDC_PASSWORD,str,sizeof(str));
				if (strcmp(str,PASSWORDMASK)!=0) {
					CallService(MS_DB_CRYPT_ENCODESTRING,sizeof(str),(LPARAM)str);
					dbv.pszVal=NULL;
					if(DBGetContactSetting(NULL,network->m_szModuleName,QQ_PASSWORD,&dbv) || strcmp(str,dbv.pszVal))
						reconnectRequired=1;
				
					
					if(dbv.pszVal!=NULL) DBFreeVariant(&dbv);
					DBWriteContactSettingString(NULL,network->m_szModuleName,QQ_PASSWORD,str);
				}

				// Server list
				GetDlgItemTextA(hwndDlg,IDC_SERVER,str,sizeof(str));
				if(DBGetContactSetting(NULL,network->m_szModuleName,QQ_LOGINSERVER2,&dbv) || strcmp(str,dbv.pszVal))
					reconnectRequired=1;
					
				if(dbv.pszVal!=NULL) DBFreeVariant(&dbv);
				DBWriteContactSettingString(NULL,network->m_szModuleName,QQ_LOGINSERVER2,str);

				CHECK_BYTE_SETTING(QQ_INVISIBLE,IDC_FORCEINVISIBLE);
				WRITE_CHECK_SETTING(QQ_INVISIBLE,IDC_FORCEINVISIBLE);

				CHECK_BYTE_SETTING(QQ_FORCEUNICODE,IDC_FORCEUNICODE);
				WRITE_CHECK_SETTING(QQ_FORCEUNICODE,IDC_FORCEUNICODE);

				/*
				CHECK_BYTE_SETTING2(QQ_NOAUTOSERVER,IDC_AUTOSERVER);
				WRITE_CHECK_SETTING2(QQ_NOAUTOSERVER,IDC_AUTOSERVER);
				*/

				if(Packet::isClientKeySet() && reconnectRequired) MessageBox(hwndDlg,TranslateT("The changes you have made require you to reconnect to the QQ network before they take effect"),APPNAME,MB_OK);

				DBWriteContactSettingByte(NULL,network->m_szModuleName,QQ_MESSAGECONVERSION,(BYTE)SendDlgItemMessage(hwndDlg,IDC_CONVERSION,CB_GETCURSEL,0,0));

				return TRUE;
			}
			break;
	}
	return FALSE;
}
Esempio n. 26
0
/**
   Get the CPU time for the specified process
*/
unsigned long proc_get_jiffies(process_t *p)
{
    wchar_t fn[FN_SIZE];

    char state;
    int pid, ppid, pgrp,
        session, tty_nr, tpgid,
        exit_signal, processor;

    long int cutime, cstime, priority,
         nice, placeholder, itrealvalue,
         rss;
    unsigned long int flags, minflt, cminflt,
             majflt, cmajflt, utime,
             stime, starttime, vsize,
             rlim, startcode, endcode,
             startstack, kstkesp, kstkeip,
             signal, blocked, sigignore,
             sigcatch, wchan, nswap, cnswap;
    char comm[1024];

    if (p->pid <= 0)
        return 0;

    swprintf(fn, FN_SIZE, L"/proc/%d/stat", p->pid);

    FILE *f = wfopen(fn, "r");
    if (!f)
        return 0;

    int count = fscanf(f,
                       "%d %s %c "
                       "%d %d %d "
                       "%d %d %lu "

                       "%lu %lu %lu "
                       "%lu %lu %lu "
                       "%ld %ld %ld "

                       "%ld %ld %ld "
                       "%lu %lu %ld "
                       "%lu %lu %lu "

                       "%lu %lu %lu "
                       "%lu %lu %lu "
                       "%lu %lu %lu "

                       "%lu %d %d ",

                       &pid, comm, &state,
                       &ppid, &pgrp, &session,
                       &tty_nr, &tpgid, &flags,

                       &minflt, &cminflt, &majflt,
                       &cmajflt, &utime, &stime,
                       &cutime, &cstime, &priority,

                       &nice, &placeholder, &itrealvalue,
                       &starttime, &vsize, &rss,
                       &rlim, &startcode, &endcode,

                       &startstack, &kstkesp, &kstkeip,
                       &signal, &blocked, &sigignore,
                       &sigcatch, &wchan, &nswap,

                       &cnswap, &exit_signal, &processor
                      );

    if (count < 17)
    {
        return 0;
    }

    /*
      Don't need to check exit status of fclose on read-only streams
    */
    fclose(f);
    return utime+stime+cutime+cstime;

}
Esempio n. 27
0
DWORD PipeReader::startServer() {
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = FALSE;  
	CreateMyDACL(&sa);

	wchar_t temp[300];
	swprintf(temp,L"\\\\.\\pipe\\%s",pipeName);
	HANDLE _pipe=CreateNamedPipe(temp,PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,PIPE_TYPE_BYTE,PIPE_UNLIMITED_INSTANCES,0,0,0,&sa);
	swprintf(temp,L"\\\\.\\pipe\\%s",pipeEventName);
	HANDLE _eventpipe=CreateNamedPipe(temp,PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,PIPE_TYPE_BYTE,PIPE_UNLIMITED_INSTANCES,0,0,0,&sa);
	wchar_t log[300];
	swprintf(log,L"[BixVReader]Pipe created:%s:%08Ix",pipeName,_pipe);
	OutputDebugString(log);

	while (true) {
		//__try {
			BOOL ris=ConnectNamedPipe(_pipe,NULL);
			if (ris==0) {
				swprintf(log,L"[BixVReader]Pipe NOT connected:%x",GetLastError());
				OutputDebugString(log);
			}
			else {
				swprintf(log,L"[BixVReader]Pipe connected");
				OutputDebugString(log);
				}
			ris=ConnectNamedPipe(_eventpipe,NULL);
			if (ris==0) {
				swprintf(log,L"[BixVReader]Event Pipe NOT connected:%x",GetLastError());
				OutputDebugString(log);
			}
			else {
				swprintf(log,L"[BixVReader]Event Pipe connected");
				OutputDebugString(log);
			}
			pipe=_pipe;
			eventpipe=_eventpipe;
			if (waitInsertIpr!=NULL) {
				SectionLocker lock(device->m_RequestLock);
				// if I'm waiting for card insertion, verify if there's a card present
				if (initProtocols()) {
					if (waitInsertIpr->UnmarkCancelable()==S_OK)
						waitInsertIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
					waitInsertIpr=NULL;
					state=SCARD_SWALLOWED;					
				}
			}
			
			while (true) {
				// wait for a command
				DWORD command=0;
				DWORD read=0;
				if (!ReadFile(eventpipe,&command,sizeof(DWORD),&read,NULL)) {
					state=SCARD_ABSENT;
					OutputDebugString(L"[BixVReader]Pipe error");
					powered=0;
					pipe=NULL;
					eventpipe=NULL;
					if (waitRemoveIpr!=NULL) {// card inserted
						SectionLocker lock(device->m_RequestLock);
						OutputDebugString(L"[BixVReader]complete Wait Remove");
						if (waitRemoveIpr->UnmarkCancelable()==S_OK) {
							OutputDebugString(L"[BixVReader]Wait Remove Unmarked");
							waitRemoveIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
							OutputDebugString(L"[BixVReader]Wait Remove Completed");
						}
						waitRemoveIpr=NULL;
					}
					if (waitInsertIpr!=NULL) {// card removed
						SectionLocker lock(device->m_RequestLock);
						OutputDebugString(L"[BixVReader]cancel Wait Remove");
						if (waitInsertIpr->UnmarkCancelable()==S_OK) {
							OutputDebugString(L"[BixVReader]Wait Insert Unmarked");
							waitInsertIpr->CompleteWithInformation(HRESULT_FROM_WIN32(ERROR_CANCELLED), 0);
							OutputDebugString(L"[BixVReader]Wait Insert Cancelled");
						}
						waitInsertIpr=NULL;
					}
					DisconnectNamedPipe(_pipe);
					DisconnectNamedPipe(_eventpipe);
					break;
				}
				OutputDebugString(L"[BixVReader]Pipe data");
				if (command==0)
					powered=0;
				if (command==0 && waitRemoveIpr!=NULL) {// card removed
					SectionLocker lock(device->m_RequestLock);
					state=SCARD_ABSENT;
					if (waitRemoveIpr->UnmarkCancelable()==S_OK) {						
						waitRemoveIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
					}
					waitRemoveIpr=NULL;
				}
				else if (command==1 && waitInsertIpr!=NULL) {// card inserted
					SectionLocker lock(device->m_RequestLock);
					state=SCARD_SWALLOWED;
					initProtocols();
					if (waitInsertIpr->UnmarkCancelable()==S_OK) {
						waitInsertIpr->CompleteWithInformation(STATUS_SUCCESS, 0);
					}
					waitInsertIpr=NULL;
				}
			}
		//}
		//__except(EXCEPTION_EXECUTE_HANDLER) {
		//	wchar_t log[300];
		//	DWORD err=GetExceptionCode();
		//	swprintf(log,L"Exception:%08X",err);
		//	OutputDebugString(log);
		//}
	}
	OutputDebugString(L"[BixVReader]Pipe quit!!!");
	return 0;
}
Esempio n. 28
0
BOOL InstallProvider(WCHAR *pwszPathName)
{
	WCHAR wszLSPName[] = L"PhoenixLSP";
	LPWSAPROTOCOL_INFOW pProtoInfo;
	int nProtocols;
	WSAPROTOCOL_INFOW OriginalProtocolInfo[3];
	DWORD			 dwOrigCatalogId[3];
	int nArrayCount = 0;

	DWORD dwLayeredCatalogId;		// 我们分层协议的目录ID号

	int nError;
	
		// 找到我们的下层协议,将信息放入数组中
	// 枚举所有服务程序提供者
	pProtoInfo = GetProvider(&nProtocols);
	BOOL bFindUdp = FALSE;
	BOOL bFindTcp = FALSE;
	BOOL bFindRaw = FALSE;
	int i=0;
	for(i; i<nProtocols; i++)
	{
		if(pProtoInfo[i].iAddressFamily == AF_INET)
		{
		if(!bFindUdp && pProtoInfo[i].iProtocol == IPPROTO_UDP)
			{
				memcpy(&OriginalProtocolInfo[nArrayCount], &pProtoInfo[i], sizeof(WSAPROTOCOL_INFOW));
				OriginalProtocolInfo[nArrayCount].dwServiceFlags1 = 
					OriginalProtocolInfo[nArrayCount].dwServiceFlags1 & (~XP1_IFS_HANDLES); 
				
				dwOrigCatalogId[nArrayCount++] = pProtoInfo[i].dwCatalogEntryId;

				bFindUdp = TRUE;
			}

		if(!bFindTcp && pProtoInfo[i].iProtocol == IPPROTO_TCP)
			{
				memcpy(&OriginalProtocolInfo[nArrayCount], &pProtoInfo[i], sizeof(WSAPROTOCOL_INFOW));
				OriginalProtocolInfo[nArrayCount].dwServiceFlags1 = 
					OriginalProtocolInfo[nArrayCount].dwServiceFlags1 & (~XP1_IFS_HANDLES); 
				
				dwOrigCatalogId[nArrayCount++] = pProtoInfo[i].dwCatalogEntryId;

				bFindTcp = TRUE;
			} 
		if(!bFindRaw && pProtoInfo[i].iProtocol == IPPROTO_IP)
			{
				memcpy(&OriginalProtocolInfo[nArrayCount], &pProtoInfo[i], sizeof(WSAPROTOCOL_INFOW));
				OriginalProtocolInfo[nArrayCount].dwServiceFlags1 = 
					OriginalProtocolInfo[nArrayCount].dwServiceFlags1 & (~XP1_IFS_HANDLES); 
				
				dwOrigCatalogId[nArrayCount++] = pProtoInfo[i].dwCatalogEntryId;

				bFindRaw = TRUE;
			}
		}
	}  

		// 安装我们的分层协议,获取一个dwLayeredCatalogId
	// 随便找一个下层协议的结构复制过来即可
	WSAPROTOCOL_INFOW LayeredProtocolInfo;
	memcpy(&LayeredProtocolInfo, &OriginalProtocolInfo[0], sizeof(WSAPROTOCOL_INFOW));
	// 修改协议名称,类型,设置PFL_HIDDEN标志
	wcscpy(LayeredProtocolInfo.szProtocol, wszLSPName);
	LayeredProtocolInfo.ProtocolChain.ChainLen = LAYERED_PROTOCOL; // 0;
	LayeredProtocolInfo.dwProviderFlags |= PFL_HIDDEN;
	// 安装
	if(::WSCInstallProvider(&ProviderGuid, 
					pwszPathName, &LayeredProtocolInfo, 1, &nError) == SOCKET_ERROR)
	{
		return FALSE;
	}
	// 重新枚举协议,获取分层协议的目录ID号
	FreeProvider(pProtoInfo);
	pProtoInfo = GetProvider(&nProtocols);
	for(i=0; i<nProtocols; i++)
	{
		if(memcmp(&pProtoInfo[i].ProviderId, &ProviderGuid, sizeof(ProviderGuid)) == 0)
		{
			dwLayeredCatalogId = pProtoInfo[i].dwCatalogEntryId;
			break;
		}
	}

			// 安装协议链
	// 修改协议名称,类型
	WCHAR wszChainName[WSAPROTOCOL_LEN + 1];
	for(i=0; i<nArrayCount; i++)
	{
		swprintf(wszChainName, L"%ws over %ws", wszLSPName, OriginalProtocolInfo[i].szProtocol);
		wcscpy(OriginalProtocolInfo[i].szProtocol, wszChainName);
		if(OriginalProtocolInfo[i].ProtocolChain.ChainLen == 1)
		{
			OriginalProtocolInfo[i].ProtocolChain.ChainEntries[1] = dwOrigCatalogId[i];
		}
		else
		{
			for(int j = OriginalProtocolInfo[i].ProtocolChain.ChainLen; j>0; j--)
			{
				OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j] 
									= OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j-1];
			}
		}
		OriginalProtocolInfo[i].ProtocolChain.ChainLen ++;
		OriginalProtocolInfo[i].ProtocolChain.ChainEntries[0] = dwLayeredCatalogId;	
	}
	// 获取一个Guid,安装之
	GUID ProviderChainGuid;
	if(::UuidCreate(&ProviderChainGuid) == RPC_S_OK)
	{
		if(::WSCInstallProvider(&ProviderChainGuid, 
					pwszPathName, OriginalProtocolInfo, nArrayCount, &nError) == SOCKET_ERROR)
		{
			return FALSE;	
		}
	}
	else
		return FALSE;

			// 重新排序Winsock目录,将我们的协议链提前
	// 重新枚举安装的协议
	FreeProvider(pProtoInfo);
	pProtoInfo = GetProvider(&nProtocols);

	DWORD dwIds[20];
	int nIndex = 0;
	// 添加我们的协议链
	for(i=0; i<nProtocols; i++)
	{
		if((pProtoInfo[i].ProtocolChain.ChainLen > 1) &&
					(pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId))
			dwIds[nIndex++] = pProtoInfo[i].dwCatalogEntryId;
	}
	// 添加其它协议
	for(i=0; i<nProtocols; i++)
	{
		if((pProtoInfo[i].ProtocolChain.ChainLen <= 1) ||
				(pProtoInfo[i].ProtocolChain.ChainEntries[0] != dwLayeredCatalogId))
			dwIds[nIndex++] = pProtoInfo[i].dwCatalogEntryId;
	}
	// 重新排序Winsock目录
	if((nError = ::WSCWriteProviderOrder(dwIds, nIndex)) != ERROR_SUCCESS)
	{
		return FALSE;
	}
	FreeProvider(pProtoInfo);

	return TRUE;
}
Esempio n. 29
0
/*enumerate directories*/
GF_EXPORT
GF_Err gf_enum_directory(const char *dir, Bool enum_directory, gf_enum_dir_item enum_dir_fct, void *cbck, const char *filter)
{
#ifdef WIN32
	wchar_t item_path[GF_MAX_PATH];
#else
	char item_path[GF_MAX_PATH];
#endif
	GF_FileEnumInfo file_info;

#if defined(_WIN32_WCE)
	char _path[GF_MAX_PATH];
	unsigned short path[GF_MAX_PATH];
	unsigned short w_filter[GF_MAX_PATH];
	char file[GF_MAX_PATH];
#elif defined(WIN32)
	wchar_t path[GF_MAX_PATH], *file;
	wchar_t w_filter[GF_MAX_PATH];
	wchar_t w_dir[GF_MAX_PATH];
	char *mbs_file, *mbs_item_path;
#else
	char path[GF_MAX_PATH], *file;
#endif

#ifdef WIN32
	WIN32_FIND_DATAW FindData;
	HANDLE SearchH;
#else
	DIR *the_dir;
	struct dirent* the_file;
	struct stat st;
#endif

	if (!dir || !enum_dir_fct) return GF_BAD_PARAM;

	if (filter && (!strcmp(filter, "*") || !filter[0])) filter=NULL;

	memset(&file_info, 0, sizeof(GF_FileEnumInfo) );

	if (!strcmp(dir, "/")) {
#if defined(WIN32) && !defined(_WIN32_WCE)
		u32 len;
		char *drives, *volume;
		len = GetLogicalDriveStrings(0, NULL);
		drives = (char*)gf_malloc(sizeof(char)*(len+1));
		drives[0]=0;
		GetLogicalDriveStrings(len, drives);
		len = (u32) strlen(drives);
		volume = drives;
		file_info.directory = GF_TRUE;
		file_info.drive = GF_TRUE;
		while (len) {
			enum_dir_fct(cbck, volume, "", &file_info);
			volume += len+1;
			len = (u32) strlen(volume);
		}
		gf_free(drives);
		return GF_OK;
#elif defined(__SYMBIAN32__)
		RFs iFs;
		TDriveList aList;
		iFs.Connect();
		iFs.DriveList(aList);
		for (TInt i=0; i<KMaxDrives; i++) {
			if (aList[i]) {
				char szDrive[10];
				TChar aDrive;
				iFs.DriveToChar(i, aDrive);
				sprintf(szDrive, "%c:", (TUint)aDrive);
				enum_dir_fct(cbck, szDrive, "", &file_info);
			}
		}
		iFs.Close();
		FlushItemList();
		return GF_OK;
#endif
	}


#if defined (_WIN32_WCE)
	switch (dir[strlen(dir) - 1]) {
	case '/':
	case '\\':
		sprintf(_path, "%s*", dir);
		break;
	default:
		sprintf(_path, "%s%c*", dir, GF_PATH_SEPARATOR);
		break;
	}
	CE_CharToWide(_path, path);
	CE_CharToWide((char *)filter, w_filter);
#elif defined(WIN32)
	{
		const char* tmpdir = dir;
		gf_utf8_mbstowcs(w_dir, sizeof(w_dir), &tmpdir);
	}
	switch (w_dir[wcslen(w_dir) - 1]) {
	case '/':
	case '\\':
		swprintf(path, MAX_PATH, L"%s*", w_dir);
		break;
	default:
		swprintf(path, MAX_PATH, L"%s%c*", w_dir, GF_PATH_SEPARATOR);
		break;
	}
	{
		const char* tmpfilter = filter;
		gf_utf8_mbstowcs(w_filter, sizeof(w_filter), &tmpfilter);
	}
#else
	strcpy(path, dir);
	if (path[strlen(path)-1] != '/') strcat(path, "/");
#endif

#ifdef WIN32
	SearchH= FindFirstFileW(path, &FindData);
	if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR;

#if defined (_WIN32_WCE)
	_path[strlen(_path)-1] = 0;
#else
	path[wcslen(path)-1] = 0;
#endif

	while (SearchH != INVALID_HANDLE_VALUE) {

#else

	the_dir = opendir(path);
	if (the_dir == NULL) {
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot open directory %s for enumeration: %d\n", path, errno));
		return GF_IO_ERR;
	}
	the_file = readdir(the_dir);
	while (the_file) {

#endif

		memset(&file_info, 0, sizeof(GF_FileEnumInfo) );


#if defined (_WIN32_WCE)
		if (!wcscmp(FindData.cFileName, _T(".") )) goto next;
		if (!wcscmp(FindData.cFileName, _T("..") )) goto next;
#elif defined(WIN32)
		if (!wcscmp(FindData.cFileName, L".")) goto next;
		if (!wcscmp(FindData.cFileName, L"..")) goto next;
#else
		if (!strcmp(the_file->d_name, "..")) goto next;
		if (the_file->d_name[0] == '.') goto next;
#endif

#ifdef WIN32
		file_info.directory = (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? GF_TRUE : GF_FALSE;
		if (!enum_directory && file_info.directory) goto next;
		if (enum_directory && !file_info.directory) goto next;
#endif

		if (filter) {
#if defined (_WIN32_WCE)
			short ext[30];
			short *sep = wcsrchr(FindData.cFileName, (wchar_t) '.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#elif defined(WIN32)
			wchar_t ext[30];
			wchar_t *sep = wcsrchr(FindData.cFileName, L'.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#else
			char ext[30];
			char *sep = strrchr(the_file->d_name, '.');
			if (!sep) goto next;
			strcpy(ext, sep+1);
			strlwr(ext);
			if (!strstr(filter, sep+1)) goto next;
#endif
		}

#if defined(WIN32)
		file_info.hidden = (FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ? GF_TRUE : GF_FALSE;
		file_info.system = (FindData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? GF_TRUE : GF_FALSE;
		file_info.size = MAXDWORD;
		file_info.size += 1;
		file_info.size *= FindData.nFileSizeHigh;
		file_info.size += FindData.nFileSizeLow;
		file_info.last_modified = (u64) ((*(LONGLONG *) &FindData.ftLastWriteTime - TIMESPEC_TO_FILETIME_OFFSET) / 10000000);
#endif

#if defined (_WIN32_WCE)
		CE_WideToChar(FindData.cFileName, file);
		strcpy(item_path, _path);
		strcat(item_path, file);
#elif defined(WIN32)
		wcscpy(item_path, path);
		wcscat(item_path, FindData.cFileName);
		file = FindData.cFileName;
#else
		strcpy(item_path, path);
		strcat(item_path, the_file->d_name);
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] Checking file %s for enum\n", item_path));

		if (stat( item_path, &st ) != 0) goto next;

		file_info.directory = ((st.st_mode & S_IFMT) == S_IFDIR) ? GF_TRUE : GF_FALSE;
		if (enum_directory && !file_info.directory) goto next;
		if (!enum_directory && file_info.directory) goto next;

		file_info.size = st.st_size;

		{
			struct tm _t = * gmtime(& st.st_mtime);
			file_info.last_modified = mktime(&_t);
		}
		file = the_file->d_name;
		if (file && file[0]=='.') file_info.hidden = 1;

		if (file_info.directory) {
			char * parent_name = strrchr(item_path, '/');
			if (!parent_name) {
				file_info.drive = GF_TRUE;
			} else {
				struct stat st_parent;
				parent_name[0] = 0;
				if (stat(item_path, &st_parent) == 0)  {
					if ((st.st_dev != st_parent.st_dev) || ((st.st_dev == st_parent.st_dev) && (st.st_ino == st_parent.st_ino))) {
						file_info.drive = GF_TRUE;
					}
				}
				parent_name[0] = '/';
			}
		}
#endif

#ifdef WIN32
		mbs_file = wcs_to_utf8(file);
		mbs_item_path = wcs_to_utf8(item_path);
		if (!mbs_file || !mbs_item_path)
		{
			if (mbs_file) gf_free(mbs_file);
			if (mbs_item_path) gf_free(mbs_item_path);
			return GF_IO_ERR;
		}
		if (enum_dir_fct(cbck, mbs_file, mbs_item_path, &file_info)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(1) the following error code: %d\n", err));
			}
#else
		if (enum_dir_fct(cbck, file, item_path, &file_info)) {
#endif
			break;
		}

#ifdef WIN32
		gf_free(mbs_file);
		gf_free(mbs_item_path);
#endif

next:
#ifdef WIN32
		if (!FindNextFileW(SearchH, &FindData)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(2) the following error code: %d\n", err));
			}
			break;
		}
#else
		the_file = readdir(the_dir);
#endif
	}
#ifndef WIN32
	closedir(the_dir);
#endif
	return GF_OK;
}

GF_EXPORT
u64 gf_ftell(FILE *fp)
{
#if defined(_WIN32_WCE)
	return (u64) ftell(fp);
#elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) ftello64(fp);
#else
	return (u64) ftell(fp);
#endif
#elif defined(WIN32)
	return (u64) _ftelli64(fp);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return (u64) ftello64(fp);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return (u64) ftello(fp);
#else
	return (u64) ftell(fp);
#endif
}

GF_EXPORT
u64 gf_fseek(FILE *fp, s64 offset, s32 whence)
{
#if defined(_WIN32_WCE)
	return (u64) fseek(fp, (s32) offset, whence);
#elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) fseeko64(fp, offset, whence);
#else
	return (u64) fseek(fp, (s32) offset, whence);
#endif
#elif defined(WIN32)
	return (u64) _fseeki64(fp, offset, whence);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return fseeko64(fp, (off64_t) offset, whence);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return fseeko(fp, (off_t) offset, whence);
#else
	return fseek(fp, (s32) offset, whence);
#endif
}

GF_EXPORT
FILE *gf_fopen(const char *file_name, const char *mode)
{
	FILE *res = NULL;

#if defined(WIN32)
	wchar_t *wname;
	wchar_t *wmode;

	wname = utf8_to_wcs(file_name);
	wmode = utf8_to_wcs(mode);
	if (!wname || !wmode)
	{
		if (wname) gf_free(wname);
		if (wmode) gf_free(wmode);
		return NULL;
	}
	res = _wfsopen(wname, wmode, _SH_DENYNO);
	gf_free(wname);
	gf_free(wmode);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	res = fopen64(file_name, mode);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	res = fopen(file_name, mode);
#else
	res = fopen(file_name, mode);
#endif

	if (res) {
		gpac_file_handles++;
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] file %s opened in mode %s - %d file handles\n", file_name, mode, gpac_file_handles));
	} else {
		if (strchr(mode, 'w') || strchr(mode, 'a')) {
#if defined(WIN32)
			u32 err = GetLastError();
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: 0x%08x\n", file_name, mode, err));
#else
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: %d\n", file_name, mode, errno));
#endif
		}
	}
	return res;
}

GF_EXPORT
s32 gf_fclose(FILE *file)
{
	if (file) {
		assert(gpac_file_handles);
		gpac_file_handles--;
	}
	return fclose(file);
}

#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE) && !defined(WIN32)
#define HAVE_STRERROR_R 1
#endif

GF_EXPORT
size_t gf_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
	return fread(ptr, size, nmemb, stream);
}

GF_EXPORT
size_t gf_fwrite(const void *ptr, size_t size, size_t nmemb,
                 FILE *stream)
{
	size_t result = fwrite(ptr, size, nmemb, stream);
	if (result != nmemb) {
#ifdef _WIN32_WCE
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data: %d blocks to write but %d blocks written\n", nmemb, result));
#else
#if defined WIN32 && !defined(GPAC_CONFIG_WIN32)
		errno_t errno_save;
		_get_errno(&errno_save);
#else
		int errno_save = errno;
#endif
		//if (errno_save!=0)
		{
#ifdef HAVE_STRERROR_R
#define ERRSTR_BUF_SIZE 256
			char errstr[ERRSTR_BUF_SIZE];
			if(strerror_r(errno_save, errstr, ERRSTR_BUF_SIZE) != 0)
			{
				strerror_r(0, errstr, ERRSTR_BUF_SIZE);
			}
#else
			char *errstr = (char*)strerror(errno_save);
#endif
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data (%s): %d blocks to write but %d blocks written\n", errstr, nmemb, result));
		}
#endif
	}
	return result;
}
Esempio n. 30
0
bool UPnP::Create(WORD Port)
{
	IUPnPNAT * Nat = NULL;
	IStaticPortMappingCollection * PortMappingCollection = NULL;
	IStaticPortMapping * PortMap = NULL;
	HRESULT Result;
	wchar_t Protocol[256];
	wchar_t InternalClient[256];
	wchar_t Description[256];

	Destroy();

	TRACE("UPnP: Adding port\n");

	if(!GetIp())
	{
		return false;
	}

	mbstowcs(InternalClient, m_Address, 256);
//	swprintf(Protocol, L"TCP");
//	swprintf(Description, L"Torrent");

	swprintf(Protocol, L"UDP");
	swprintf(Description, L"Gunz");

	// Create IUPnPNat
	Result = CoCreateInstance(CLSID_UPnPNAT, NULL, CLSCTX_INPROC_SERVER, IID_IUPnPNAT, (void **)&Nat);
	if(FAILED(Result))
	{
		TRACE("UPnP: Unable to create UPnPNAT interface\n");
		return false;
	}

	Result = Nat->get_StaticPortMappingCollection(&PortMappingCollection);

	if(!PortMappingCollection || FAILED(Result))
	{
		if(PortMappingCollection) PortMappingCollection->Release();
		Nat->Release();

		TRACE("UPnP: Unable to acquire a static portmapping collection\n");
		return false;
	}

	Result = PortMappingCollection->Add(Port, Protocol, Port, InternalClient, VARIANT_TRUE, Description, &PortMap);

	if(!PortMap || FAILED(Result))
	{
		if(PortMap) PortMap->Release();
		PortMappingCollection->Release();
		Nat->Release();

		TRACE("UPnP: Unable add port\n");
		return false;
	}

	TRACE("UPnP: Port %d forwarded to %s\n", Port, m_Address);

	PortMap->Release();
	PortMappingCollection->Release();
	Nat->Release();

	m_Port = Port;

	return true;
}