static void sttFillJidList(HWND hwndDlg)
{
	JABBER_MUC_JIDLIST_INFO *jidListInfo;
	HXML iqNode, queryNode;
	const TCHAR* from, *jid, *reason, *nick;
	LVITEM lvi;
	HWND hwndList;
	int count, i;

	TCHAR *filter = NULL;
	if (GetWindowLongPtr(GetDlgItem(hwndDlg, IDC_FILTER), GWLP_USERDATA))
	{
		int filterLength = GetWindowTextLength(GetDlgItem(hwndDlg, IDC_FILTER)) + 1;
		filter = (TCHAR *)_alloca(filterLength * sizeof(TCHAR));
		GetDlgItemText(hwndDlg, IDC_FILTER, filter, filterLength);
	}

	jidListInfo = ( JABBER_MUC_JIDLIST_INFO * ) GetWindowLongPtr( hwndDlg, GWLP_USERDATA );
	if ( !jidListInfo )
		return;

	hwndList = GetDlgItem( hwndDlg, IDC_LIST );
	SendMessage(hwndList, WM_SETREDRAW, FALSE, 0);

	count = ListView_GetItemCount( hwndList );
	lvi.mask = LVIF_PARAM;
	lvi.iSubItem = 0;
	for ( i=0; i<count; i++ ) {
		lvi.iItem = i;
		if ( ListView_GetItem( hwndList, &lvi ) == TRUE ) {
			if ( lvi.lParam!=( LPARAM )( -1 ) && lvi.lParam!=( LPARAM )( NULL )) {
				mir_free(( void * ) lvi.lParam );
			}
		}
	}
	ListView_DeleteAllItems( hwndList );

	// Populate displayed list from iqNode
	if (( iqNode = jidListInfo->iqNode ) != NULL ) {
		if (( from = xmlGetAttrValue( iqNode, _T("from"))) != NULL ) {
			if (( queryNode = xmlGetChild( iqNode , "query" )) != NULL ) {
				lvi.mask = LVIF_TEXT | LVIF_PARAM;
				lvi.iSubItem = 0;
				lvi.iItem = 0;
				for ( i=0; ; i++ ) {
					HXML itemNode = xmlGetChild( queryNode ,i);
					if ( !itemNode )
						break;

					if (( jid = xmlGetAttrValue( itemNode, _T("jid"))) != NULL ) {
						lvi.pszText = ( TCHAR* )jid;
						if ( jidListInfo->type == MUC_BANLIST ) {
							if (( reason = xmlGetText(xmlGetChild( itemNode , "reason" ))) != NULL ) {
								TCHAR jidreason[ JABBER_MAX_JID_LEN + 256 ];
								mir_sntprintf( jidreason, SIZEOF( jidreason ), _T("%s (%s)") , jid, reason );
								lvi.pszText = jidreason;
						}	}

						if ( jidListInfo->type == MUC_VOICELIST || jidListInfo->type == MUC_MODERATORLIST ) {
							if (( nick = xmlGetAttrValue( itemNode, _T("nick"))) != NULL ) {
								TCHAR nickjid[ JABBER_MAX_JID_LEN + 256 ];
								mir_sntprintf( nickjid, SIZEOF( nickjid ), _T("%s (%s)") , nick, jid );
								lvi.pszText = nickjid;
						}	}

						if (filter && *filter && !JabberStrIStr(lvi.pszText, filter))
							continue;

						lvi.lParam = ( LPARAM )mir_tstrdup( jid );

						ListView_InsertItem( hwndList, &lvi );
						lvi.iItem++;
	}	}	}	}	}

	lvi.mask = LVIF_PARAM;
	lvi.lParam = ( LPARAM )( -1 );
	ListView_InsertItem( hwndList, &lvi );

	SendMessage(hwndList, WM_SETREDRAW, TRUE, 0);
	RedrawWindow(hwndList, NULL, NULL, RDW_INVALIDATE);
}
/*
================
DialogDeclEditor::LoadDecl
================
*/
void DialogDeclEditor::LoadDecl(idDecl *decl)
{
	int numLines = 0;
	int numCharsPerLine = 0;
	int maxCharsPerLine = 0;
	idStr declText;
	CRect rect;

	this->decl = decl;

	switch (decl->GetType()) {
		case DECL_ENTITYDEF:
			declEdit.SetStringColor(SRE_COLOR_BLUE, SRE_COLOR_DARK_CYAN);
			declEdit.LoadKeyWordsFromFile("editors/entity.def");
			break;
		case DECL_MATERIAL:
			declEdit.LoadKeyWordsFromFile("editors/material.def");
			break;
		case DECL_SKIN:
			declEdit.LoadKeyWordsFromFile("editors/skin.def");
			break;
		case DECL_SOUND:
			declEdit.LoadKeyWordsFromFile("editors/sound.def");
			break;
		case DECL_FX:
			declEdit.LoadKeyWordsFromFile("editors/fx.def");
			break;
		case DECL_PARTICLE:
			declEdit.LoadKeyWordsFromFile("editors/particle.def");
			break;
		case DECL_AF:
			declEdit.LoadKeyWordsFromFile("editors/af.def");
			break;
		case DECL_TABLE:
			declEdit.LoadKeyWordsFromFile("editors/table.def");
			break;
		case DECL_MODELDEF:
			declEdit.LoadKeyWordsFromFile("editors/model.def");
			break;
		default:
			declEdit.LoadKeyWordsFromFile(va("editors/%s.def", declManager->GetDeclNameFromType(decl->GetType())));
			break;
	}

	firstLine = decl->GetLineNum();

	char *localDeclText = (char *)_alloca((decl->GetTextLength() + 1) * sizeof(char));
	decl->GetText(localDeclText);
	declText = localDeclText;

	// clean up new-line crapola
	declText.Replace("\r", "");
	declText.Replace("\n", "\r");
	declText.Replace("\v", "\r");
	declText.StripLeading('\r');
	declText.Append("\r");

	declEdit.SetText(declText);

	for (const char *ptr = declText.c_str(); *ptr; ptr++) {
		if (*ptr == '\r') {
			if (numCharsPerLine > maxCharsPerLine) {
				maxCharsPerLine = numCharsPerLine;
			}

			numCharsPerLine = 0;
			numLines++;
		} else if (*ptr == '\t') {
			numCharsPerLine += TAB_SIZE;
		} else {
			numCharsPerLine++;
		}
	}

	SetWindowText(va("Declaration Editor (%s, line %d)", decl->GetFileName(), decl->GetLineNum()));

	rect.left = initialRect.left;
	rect.right = rect.left + maxCharsPerLine * FONT_WIDTH + 32;
	rect.top = initialRect.top;
	rect.bottom = rect.top + numLines * (FONT_HEIGHT+8) + 24 + 56;

	if (rect.right < initialRect.right) {
		rect.right = initialRect.right;
	} else if (rect.right - rect.left > 1024) {
		rect.right = rect.left + 1024;
	}

	if (rect.bottom < initialRect.bottom) {
		rect.bottom = initialRect.bottom;
	} else if (rect.bottom - rect.top > 768) {
		rect.bottom = rect.top + 768;
	}

	MoveWindow(rect);

	testButton.EnableWindow(FALSE);
	okButton.EnableWindow(FALSE);

	UpdateStatusBar();

	declEdit.SetFocus();
}
// pszDescription points to a string with the reason
// buf points to the first data after the string
void CIcqProto::handleFileRequest(PBYTE buf, WORD wLen, DWORD dwUin, DWORD dwCookie, DWORD dwID1, DWORD dwID2, char* pszDescription, int nVersion, BOOL bDC)
{
	BOOL bEmptyDesc = FALSE;
	if (strlennull(pszDescription) == 0) {
		pszDescription = Translate("No description given");
		bEmptyDesc = TRUE;
	}

	// Empty port+pad
	buf += 4;
	wLen -= 4;

	// Filename
	WORD wFilenameLength;
	unpackLEWord(&buf, &wFilenameLength);
	if (!wFilenameLength) {
		NetLog_Direct("Ignoring malformed file send request");
		return;
	}

	char *pszFileName = (char*)_alloca(wFilenameLength + 1);
	unpackString(&buf, pszFileName, wFilenameLength);
	pszFileName[wFilenameLength] = '\0';

	wLen = wLen - 2 - wFilenameLength;

	// Total filesize
	DWORD dwFileSize;
	unpackLEDWord(&buf, &dwFileSize);
	wLen -= 4;

	int bAdded;
	MCONTACT hContact = HContactFromUIN(dwUin, &bAdded);

	// Initialize a filetransfer struct
	filetransfer *ft = CreateFileTransfer(hContact, dwUin, nVersion);
	ft->dwCookie = dwCookie;
	ft->szFilename = mir_strdup(pszFileName);
	ft->szDescription = 0;
	ft->fileId = -1;
	ft->dwTotalSize = dwFileSize;
	ft->pMessage.dwMsgID1 = dwID1;
	ft->pMessage.dwMsgID2 = dwID2;
	ft->bDC = bDC;
	ft->bEmptyDesc = bEmptyDesc;

	// Send chain event
	TCHAR* ptszFileName = mir_utf8decodeT(pszFileName);

	PROTORECVFILET pre = { 0 };
	pre.flags = PREF_TCHAR;
	pre.fileCount = 1;
	pre.timestamp = time(NULL);
	pre.tszDescription = mir_utf8decodeT(pszDescription);
	pre.ptszFiles = &ptszFileName;
	pre.lParam = (LPARAM)ft;
	ProtoChainRecvFile(hContact, &pre);

	mir_free(pre.tszDescription);
	mir_free(ptszFileName);
}
/*
====================
R_OrderIndexes

Reorganizes the indexes so they will take best advantage
of the internal GPU vertex caches
====================
*/
void R_OrderIndexes( int numIndexes, glIndex_t *indexes ) {
	bool	*triangleUsed;
	int			numTris;
	glIndex_t	*oldIndexes;
	glIndex_t	*base;
	int			numOldIndexes;
	int			tri;
	int			i;
	vertRef_t	*vref, **vrefs, *vrefTable;
	int			numVerts;
	int			v1, v2;
	int			c_starts;
	//int			c_cost;

	if ( !r_orderIndexes.GetBool() ) {
		return;
	}

	// save off the original indexes
	oldIndexes = (glIndex_t *)_alloca( numIndexes * sizeof( *oldIndexes ) );
	memcpy( oldIndexes, indexes, numIndexes * sizeof( *oldIndexes ) );
	numOldIndexes = numIndexes;

	// make a table to mark the triangles when they are emited
	numTris = numIndexes / 3;
	triangleUsed = (bool *)_alloca( numTris * sizeof( *triangleUsed ) );
	memset( triangleUsed, 0, numTris * sizeof( *triangleUsed ) );

	// find the highest vertex number
	numVerts = 0;
	for ( i = 0 ; i < numIndexes ; i++ ) {
		if ( indexes[i] > numVerts ) {
			numVerts = indexes[i];
		}
	}
	numVerts++;

	// create a table of triangles used by each vertex
	vrefs = (vertRef_t **)_alloca( numVerts * sizeof( *vrefs ) );
	memset( vrefs, 0, numVerts * sizeof( *vrefs ) );

	vrefTable = (vertRef_t *)_alloca( numIndexes * sizeof( *vrefTable ) );
	for ( i = 0 ; i < numIndexes ; i++ ) {
		tri = i / 3;

		vrefTable[i].tri = tri;
		vrefTable[i].next = vrefs[oldIndexes[i]];
		vrefs[oldIndexes[i]] = &vrefTable[i];
	}

	// generate new indexes
	numIndexes = 0;
	c_starts = 0;
	while ( numIndexes != numOldIndexes ) {
		// find a triangle that hasn't been used
		for ( tri = 0 ; tri < numTris ; tri++ ) {
			if ( !triangleUsed[tri] ) {
				break;
			}
		}
		if ( tri == numTris ) {
			common->Error( "R_OrderIndexes: ran out of unused tris" );
		}

		c_starts++;

		do {
			// emit this tri
			base = oldIndexes + tri * 3;
			indexes[numIndexes+0] = base[0];
			indexes[numIndexes+1] = base[1];
			indexes[numIndexes+2] = base[2];
			numIndexes += 3;

			triangleUsed[tri] = true;

			// try to find a shared edge to another unused tri
			for ( i = 0 ; i < 3 ; i++ ) {
				v1 = base[i];
				v2 = base[(i+1)%3];

				for ( vref = vrefs[v1] ; vref ; vref = vref->next ) {
					tri = vref->tri;
					if ( triangleUsed[tri] ) {
						continue;
					}

					// if this triangle also uses v2, grab it
					if ( oldIndexes[tri*3+0] == v2
						|| oldIndexes[tri*3+1] == v2
						|| oldIndexes[tri*3+2] == v2 ) {
						break;
					}
				}
				if ( vref ) {
					break;
				}
			}

			// if we couldn't chain off of any verts, we need to find a new one
			if ( i == 3 ) {
				break;
			}
		} while ( 1 );
	}

	//c_cost = R_MeshCost( numIndexes, indexes );

}
Exemple #5
0
BOOL CTypeInfos::GetType(IDiaSymbol* pSymbol, BOOL bBaseType )
{
    BOOL bRet;
    HRESULT hResult;
    IDiaSymbol* pBaseType;
    DWORD dwTag=SymTagNull;
    
    // until a name is found try to get name
    if (!this->Name)
    {
        BSTR Name=NULL;
        pSymbol->get_name(&Name);

        if (Name)
        {
#if (defined(UNICODE)||defined(_UNICODE))
            this->Name=_tcsdup(Name);
#else
            CAnsiUnicodeConvert::UnicodeToAnsi(Name,&this->Name);
#endif
            SysFreeString(Name);
        }
    }
    else
    {
        if ( bBaseType && (!this->TypeName) )
        {
            BSTR TypeName=NULL;
            pSymbol->get_name(&TypeName);

            if (TypeName)
            {
#if (defined(UNICODE)||defined(_UNICODE))
                this->TypeName=_tcsdup(TypeName);
#else
                CAnsiUnicodeConvert::UnicodeToAnsi(TypeName,&this->TypeName);
#endif
                SysFreeString(TypeName);
            }
        }
    }

    pSymbol->get_length(&this->Size);
    pSymbol->get_constType(&this->bConst);
    pSymbol->get_volatileType(&this->bVolatile);
    pSymbol->get_unalignedType(&this->bUnaligned);

    hResult=pSymbol->get_symTag(&dwTag);
    if(FAILED(hResult) || (dwTag==SymTagNull))
        return FALSE;

    if (this->DataKind==SymTagNull)
        this->DataKind=dwTag;

    switch(dwTag)
    {
    case SymTagUDT:
        {
            BSTR UDTName;
            if (FAILED(pSymbol->get_udtKind(&this->UserDefineTypeKind)))
                return FALSE;

            pSymbol->get_name(&UDTName);
            WCHAR* wName;
            // don't put struct / enum / class keyword info to this->TypeName
            // keep only type name
            // wName =(WCHAR*) _alloca((wcslen(rgUdtKind[this->UserDefineTypeKind])+wcslen(UDTName)+2)*sizeof(WCHAR));
            //swprintf(wName,L"%s %s",rgUdtKind[this->UserDefineTypeKind],UDTName);
            wName =(WCHAR*) _alloca((wcslen(UDTName)+1)*sizeof(WCHAR));
            wcscpy(wName,UDTName);
            this->bUserDefineType=TRUE;

#if (defined(UNICODE)||defined(_UNICODE))
            this->TypeName=_tcsdup(wName);
#else
            CAnsiUnicodeConvert::UnicodeToAnsi(wName,&this->TypeName);
#endif
            SysFreeString(UDTName);
        }
        break;

    case SymTagEnum:
        this->bEnum=TRUE;
        break;

    case SymTagFunctionType:
        this->bFunction=TRUE;
        break;

    case SymTagPointerType:
        pBaseType=0;
        pSymbol->get_reference(&this->bRefPointer);
        hResult=pSymbol->get_type(&pBaseType);
        if(FAILED(hResult) || (pBaseType==0))
            return FALSE;

        bRet=this->GetType(pBaseType,TRUE);
        this->PointerLevel++;
        pBaseType->Release();
        if (!bRet)
            return FALSE;
        break;

    case SymTagArrayType:
        pBaseType=0;
        hResult=pSymbol->get_type(&pBaseType);
        if(FAILED(hResult) || (pBaseType==0))
            return FALSE;

        // simplify , don't get array length (sized provided for local vars)
        this->PointerLevel++;
        bRet=this->GetType(pBaseType,TRUE);
        pBaseType->Release();
        if (!bRet)
            return FALSE;
        break;
    case SymTagBaseType:
        {
            WCHAR wsType[MAX_PATH];
            ULONGLONG ulLen;
            pSymbol->get_length(&ulLen); // ukLen may differ from this->Size (if pointer or other type)
            *wsType=0;

            if(FAILED(pSymbol->get_baseType(&this->BaseType)))
                return FALSE;

            switch(this->BaseType)
            {
                case btUInt :
                    wcscpy(wsType,L"unsigned ");
                // don't break btUInt to Fall through btInt
                case btInt :
                    switch(ulLen)
                    {
                        case 1:
                            wcscat(wsType,L"char");
                            break;
                        case 2:
                            wcscat(wsType,L"short");
                            break;
                        case 4:
                            wcscat(wsType,L"int");
                            break;
                        case 8:
                            wcscat(wsType,L"int64");
                            break;
                    }
                    break;
                case btFloat :
                    switch(ulLen)
                    {
                        case 4:
                            wcscpy(wsType,L"float");
                            break;
                        case 8:
                            wcscpy(wsType,L"double");
                            break;
                    }
                    break;
                }

                // if type not filled
                if(*wsType==0)
                    // get the one defined by array
                    wcscpy(wsType,rgBaseType[this->BaseType]);
            
#if (defined(UNICODE)||defined(_UNICODE))
                this->TypeName=_tcsdup(wsType);
#else
                CAnsiUnicodeConvert::UnicodeToAnsi(wsType,&this->TypeName);
#endif
        }
        break;
    case SymTagCustomType: 
        break;
    case SymTagData:
        pBaseType=0;
        hResult=pSymbol->get_type(&pBaseType);
        if(FAILED(hResult) || (pBaseType==0))
            return FALSE; // no information : can appear for local type (static can be name of local vars. Debug infos ???)

        bRet=this->GetType(pBaseType,TRUE);
        pBaseType->Release();
        if (!bRet)
            return FALSE;
        break;
    case SymTagUsingNamespace:
        break;
    case SymTagTypedef: // should not appear
        break;
    default:
#ifdef _DEBUG
        if (IsDebuggerPresent())
            DebugBreak();
#endif
        break;
    }

    return TRUE;
}
VOID EtpGpuIconUpdateCallback(
    _In_ struct _PH_NF_ICON *Icon,
    _Out_ PVOID *NewIconOrBitmap,
    _Out_ PULONG Flags,
    _Out_ PPH_STRING *NewText,
    _In_opt_ PVOID Context
    )
{
    static PH_GRAPH_DRAW_INFO drawInfo =
    {
        16,
        16,
        0,
        2,
        RGB(0x00, 0x00, 0x00),

        16,
        NULL,
        NULL,
        0,
        0,
        0,
        0
    };
    ULONG maxDataCount;
    ULONG lineDataCount;
    PFLOAT lineData1;
    HBITMAP bitmap;
    PVOID bits;
    HDC hdc;
    HBITMAP oldBitmap;
    HANDLE maxGpuProcessId;
    PPH_PROCESS_ITEM maxGpuProcessItem;
    PH_FORMAT format[8];

    // Icon

    Icon->Pointers->BeginBitmap(&drawInfo.Width, &drawInfo.Height, &bitmap, &bits, &hdc, &oldBitmap);
    maxDataCount = drawInfo.Width / 2 + 1;
    lineData1 = _alloca(maxDataCount * sizeof(FLOAT));

    lineDataCount = min(maxDataCount, EtGpuNodeHistory.Count);
    PhCopyCircularBuffer_FLOAT(&EtGpuNodeHistory, lineData1, lineDataCount);

    drawInfo.LineDataCount = lineDataCount;
    drawInfo.LineData1 = lineData1;
    drawInfo.LineColor1 = PhGetIntegerSetting(L"ColorCpuKernel");
    drawInfo.LineBackColor1 = PhHalveColorBrightness(drawInfo.LineColor1);

    if (bits)
        PhDrawGraphDirect(hdc, bits, &drawInfo);

    SelectObject(hdc, oldBitmap);
    *NewIconOrBitmap = bitmap;
    *Flags = PH_NF_UPDATE_IS_BITMAP;

    // Text

    if (EtMaxGpuNodeHistory.Count != 0)
        maxGpuProcessId = UlongToHandle(PhGetItemCircularBuffer_ULONG(&EtMaxGpuNodeHistory, 0));
    else
        maxGpuProcessId = NULL;

    if (maxGpuProcessId)
        maxGpuProcessItem = PhReferenceProcessItem(maxGpuProcessId);
    else
        maxGpuProcessItem = NULL;

    PhInitFormatS(&format[0], L"GPU Usage: ");
    PhInitFormatF(&format[1], EtGpuNodeUsage * 100, 2);
    PhInitFormatC(&format[2], '%');

    if (maxGpuProcessItem)
    {
        PhInitFormatC(&format[3], '\n');
        PhInitFormatSR(&format[4], maxGpuProcessItem->ProcessName->sr);
        PhInitFormatS(&format[5], L": ");
        PhInitFormatF(&format[6], EtGetProcessBlock(maxGpuProcessItem)->GpuNodeUsage * 100, 2);
        PhInitFormatC(&format[7], '%');
    }

    *NewText = PhFormat(format, maxGpuProcessItem ? 8 : 3, 128);
    if (maxGpuProcessItem) PhDereferenceObject(maxGpuProcessItem);
}
Exemple #7
0
void test_alloca(int n) {
  capture(_alloca(n));
  // CHECK: %[[arg:.*]] = alloca i8, i32 %{{.*}}, align 16
  // CHECK: call void @capture(i8* %[[arg]])
}
// handle Owner's avatar hash changes
void CIcqProto::handleAvatarOwnerHash(WORD wItemID, BYTE bFlags, BYTE *pData, BYTE nDataLen)
{
	if ((nDataLen >= 0x14) && m_bAvatarsEnabled)
	{
		switch (bFlags)
		{
		case 1: // our avatar is on the server
			{
				setSettingBlob(NULL, "AvatarHash", pData, 0x14); /// TODO: properly handle multiple avatar items (more formats)

				setUserInfo();
				// here we need to find a file, check its hash, if invalid get avatar from server
				TCHAR *file = GetOwnAvatarFileName();
				if (!file)
				{ // we have no avatar file, download from server
					TCHAR szFile[MAX_PATH * 2 + 4];
#ifdef _DEBUG
					debugLogA("We have no avatar, requesting from server.");
#endif
					GetAvatarFileName(0, NULL, szFile, MAX_PATH * 2);
					GetAvatarData(NULL, m_dwLocalUIN, NULL, pData, 0x14, szFile);
				}
				else
				{ // we know avatar filename
					BYTE *hash = calcMD5HashOfFile(file);

					if (!hash)
					{ // hash could not be calculated - probably missing file, get avatar from server
						TCHAR szFile[MAX_PATH * 2 + 4];
#ifdef _DEBUG
						debugLogA("We have no avatar, requesting from server.");
#endif
						GetAvatarFileName(0, NULL, szFile, MAX_PATH * 2);
						GetAvatarData(NULL, m_dwLocalUIN, NULL, pData, 0x14, szFile);
					} // check if we had set any avatar if yes set our, if not download from server
					else if (memcmp(hash, pData + 4, 0x10))
					{ // we have different avatar, sync that
						if (m_bSsiEnabled && getByte("ForceOurAvatar", 1))
						{ // we want our avatar, update hash
							DWORD dwPaFormat = ::ProtoGetAvatarFileFormat(file);
							BYTE *pHash = (BYTE*)_alloca(0x14);

							debugLogA("Our avatar is different, setting our new hash.");

							pHash[0] = 0;
							pHash[1] = dwPaFormat == PA_FORMAT_XML ? AVATAR_HASH_FLASH : AVATAR_HASH_STATIC;
							pHash[2] = 1; // state of the hash
							pHash[3] = 0x10; // len of the hash
							memcpy(pHash + 4, hash, 0x10);
							updateServAvatarHash(pHash, 0x14);
						}
						else
						{ // get avatar from server
							TCHAR tszFile[MAX_PATH * 2 + 4];
#ifdef _DEBUG
							debugLogA("We have different avatar, requesting new from server.");
#endif
							GetAvatarFileName(0, NULL, tszFile, MAX_PATH * 2);
							GetAvatarData(NULL, m_dwLocalUIN, NULL, pData, 0x14, tszFile);
						}
					}
					SAFE_FREE((void**)&hash);
					SAFE_FREE(&file);
				}
				break;
			}
		case 0x41: // request to upload avatar data
		case 0x81:
			{ // request to re-upload avatar data
				if (!m_bSsiEnabled) break; // we could not change serv-list if it is disabled...

				TCHAR *file = GetOwnAvatarFileName();
				if (!file)
				{ // we have no file to upload, remove hash from server
					debugLogA("We do not have avatar, removing hash.");
					SetMyAvatar(0, 0);
					break;
				}
				DWORD dwPaFormat = ::ProtoGetAvatarFileFormat(file);
				BYTE *hash = calcMD5HashOfFile(file);

				if (!hash)
				{ // the hash could not be calculated, remove from server
					debugLogA("We could not obtain hash, removing hash.");
					SetMyAvatar(0, 0);
				}
				else if (!memcmp(hash, pData + 4, 0x10))
				{ // we have the right file
					HANDLE hFile = NULL, hMap = NULL;
					BYTE *ppMap = NULL;
					long cbFileSize = 0;

					debugLogA("Uploading our avatar data.");

					if ((hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL )) != INVALID_HANDLE_VALUE)
						if ((hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != NULL)
							if ((ppMap = (BYTE*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
								cbFileSize = GetFileSize(hFile, NULL);

					if (cbFileSize != 0)
					{
						SetAvatarData(NULL, (WORD)(dwPaFormat == PA_FORMAT_XML ? AVATAR_HASH_FLASH : AVATAR_HASH_STATIC), ppMap, cbFileSize);
					}

					if (ppMap != NULL) UnmapViewOfFile(ppMap);
					if (hMap  != NULL) CloseHandle(hMap);
					if (hFile != NULL) CloseHandle(hFile);
					SAFE_FREE((void**)&hash);
				}
				else
				{
					BYTE *pHash = (BYTE*)_alloca(0x14);

					debugLogA("Our file is different, set our new hash.");

					pHash[0] = 0;
					pHash[1] = dwPaFormat == PA_FORMAT_XML ? AVATAR_HASH_FLASH : AVATAR_HASH_STATIC;
					pHash[2] = 1; // state of the hash
					pHash[3] = 0x10; // len of the hash
					memcpy(pHash + 4, hash, 0x10);
					updateServAvatarHash(pHash, 0x14);

					SAFE_FREE((void**)&hash);
				}

				SAFE_FREE(&file);
				break;
			}
		default:
			debugLogA("Received UNKNOWN Avatar Status.");
		}
	}
}
Exemple #9
0
int interleaved_two_of_five(struct zint_symbol *symbol, unsigned char source[], int length)
{ /* Code 2 of 5 Interleaved */

	int i, j, k, error_number;
	char bars[7], spaces[7], mixed[14], dest[1000];
#ifndef _MSC_VER
	unsigned char temp[length + 2];
#else
	unsigned char* temp = (unsigned char *)_alloca((length + 2) * sizeof(unsigned char));
#endif

	error_number = 0;
	
	if(length > 89) {
		strcpy(symbol->errtxt, "Input too long");
		return ERROR_TOO_LONG;
	}
	error_number = is_sane(NEON, source, length);
    if (error_number == ERROR_INVALID_DATA1) {
		strcpy(symbol->errtxt, "Invalid characters in data");
		return error_number;
	}
	
	ustrcpy(temp, (unsigned char *) "");
	/* Input must be an even number of characters for Interlaced 2 of 5 to work:
	   if an odd number of characters has been entered then add a leading zero */
	if (length & 1)
	{
		ustrcpy(temp, (unsigned char *) "0");
		length++;
	}
	uconcat(temp, source);

	/* start character */
	strcpy(dest, "1111");

	for(i = 0; i < length; i+=2 )
	{
		/* look up the bars and the spaces and put them in two strings */
		strcpy(bars, "");
		lookup(NEON, C25InterTable, temp[i], bars);
		strcpy(spaces, "");
		lookup(NEON, C25InterTable, temp[i + 1], spaces);

		/* then merge (interlace) the strings together */
		k = 0;
		for(j = 0; j <= 4; j++)
		{
			mixed[k] = bars[j]; k++;
			mixed[k] = spaces[j]; k++;
		}
		mixed[k] = '\0';
		concat (dest, mixed);
	}

	/* Stop character */
	concat (dest, "311");
	
	expand(symbol, dest);
	ustrcpy(symbol->text, temp);
	return error_number;

}
Exemple #10
0
void LogBase::WriteVAW(ELogMessageType type,
                         ELogMessageLevel nLevel,
                         LPCWSTR pszModule,
                         LPCWSTR pszMessage,
                         va_list args)  throw()
{
#if defined(_UNICODE) || defined(UNICODE)
    WriteVA(type, nLevel, pszModule, pszMessage, args);
#else

    if (IsFiltered(type, nLevel)) // не обрабатываем сообщение, если оно не попадает в лог
        return;
    // 75% времени тратится на new и delete, поэтому первую попытку попробуем сделать без него.
    StackResizableBuf<WCHAR, 1024> buf;
    int pos;
    for (;;)
    {
        pos = _vsnwprintf(buf.data, buf.size - 1, pszMessage, args);
        if (pos != -1)
            break;
        // BUG 16456 FIX, см. в конец WriteVAW почему
        if (buf.size >= 1024 * 256)
        {
            pos = buf.size - 1;
            break;
        }
        buf.Resize(buf.size * 2);
    }
    if (pos >= 0)
    {
        buf.data[pos] = 0;
        LPTSTR pszStr = static_cast<LPTSTR>(_alloca(buf.size));
        if (0 == WideCharToMultiByte(CP_ACP, 0/*WC_DEFAULTCHAR*/, buf.data, pos + 1, pszStr, buf.size, NULL, NULL))
        {
            _RPT1(_CRT_ERROR, "Can't convert Unicode string (error #0x%08X)", GetLastError());
            return;
        }

        LPCTSTR pszMod;
        if (pszModule == NULL)
            pszMod = m_szModule.c_str();
        else
        {
            size_t nModuleLen = wcslen(pszModule) + 1;
            LPTSTR pszModBuf = static_cast<LPTSTR>(_alloca(nModuleLen));
            if (0 == WideCharToMultiByte(CP_ACP, 0/*WC_DEFAULTCHAR*/, pszModule, nModuleLen, pszModBuf, nModuleLen, NULL, NULL))
            {
                _RPT1(_CRT_ERROR, "Can't convert Unicode string (error #0x%08X)", GetLastError());
                return;
            }
            pszMod = pszModBuf;
        }

        SYSTEMTIME st;
        GetLocalTime(&st);
        TCHAR bufdate[128], buftime[128], bufthread[128];
        _stprintf(bufdate, _T("%i-%02i-%02i"), st.wYear, st.wMonth, st.wDay);
        _stprintf(buftime, _T("%02i:%02i:%02i.%03d"), st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
        _stprintf(bufthread, _T("%03x"), GetCurrentThreadId());
        m_pMedia->Write(type, nLevel, bufdate, buftime, bufthread, GetThreadName(), pszMod, pszStr);
    }
#endif
    /* BUG 16456 FIX
    _vsnwprintf спотыкается на строках с символом 0xFFFF,
    возвращает -1 при любой длине буфера. Соответсвтвенно
    буфер увеличивается (Resize) пока не хватит памяти,
    а потом вызывается _vsnwprintf на NULL.
    Решение: Т.к. _vsnwprintf, даже если нехватает буфера, начало заполняет,
            то просто ограничим буфер 256кб (а 0 на конце и так ставим на всякий случай)

    #include <stdarg.h>
    #include <stdio.h>

    void WriteVAW(wchar_t* pszMessage, va_list args)
    {
        wchar_t buf[1000];
        int n = _vsnwprintf(buf, 1000, pszMessage, args);
        printf("Return %i\nBuf is: \"%ls\"", n, buf); // n будет -1, хотя буфера хватает !!!
    }
    void WriteW(wchar_t* pszMessage, ...)
    {
        va_list ap;
        va_start(ap, pszMessage);
        WriteVAW(pszMessage, ap);
        va_end(ap);
    }
    void main()
    {
        WriteW(L"%ls!", L"123\xffff");
    }
    */
}
void idAASBuild::GravSubdivLeafNode( idBrushBSPNode *node ) {
	int s1, s2, i, j, k, side1;
	int numSplits, numSplitters;
	idBrushBSPPortal *p1, *p2;
	idWinding *w1, *w2;
	idVec3 normal;
	idPlane plane;
	idPlaneSet planeList;
	float d, min, max;
	int *splitterOrder;
	int *bestNumSplits;
	int floor, gap, numFloorChecked;

	// if this leaf node is already classified it cannot have a combination of floor and gap portals
	if ( node->GetFlags() & (AREA_FLOOR|AREA_GAP) ) {
		return;
	}

	floor = gap = 0;

	// check if the area has a floor
	for ( p1 = node->GetPortals(); p1; p1 = p1->Next(s1) ) {
		s1 = (p1->GetNode(1) == node);

		if ( p1->GetFlags() & FACE_FLOOR ) {
			floor++;
		}
	}

	// find seperating planes between gap and floor portals
	for ( p1 = node->GetPortals(); p1; p1 = p1->Next(s1) ) {
		s1 = (p1->GetNode(1) == node);

		// if the portal is a gap seen from this side
		if ( PortalIsGap( p1, s1 ) ) {
			gap++;
			// if the area doesn't have a floor
			if ( !floor ) {
				break;
			}
		}
		else {
			continue;
		}

		numFloorChecked = 0;

		w1 = p1->GetWinding();

		// test all edges of the gap
		for ( i = 0; i < w1->GetNumPoints(); i++ ) {

			// create a plane through the edge of the gap parallel to the direction of gravity
			normal = (*w1)[(i+1)%w1->GetNumPoints()].ToVec3() - (*w1)[i].ToVec3();
			normal = normal.Cross( aasSettings->invGravityDir );
			if ( normal.Normalize() < 0.2f ) {
				continue;
			}
			plane.SetNormal( normal );
			plane.FitThroughPoint( (*w1)[i].ToVec3() );

			// get the side of the plane the gap is on
			side1 = w1->PlaneSide( plane, GRAVSUBDIV_EPSILON );
			if ( side1 == SIDE_ON ) {
				break;
			}

			// test if the plane through the edge of the gap seperates the gap from a floor portal
			for ( p2 = node->GetPortals(); p2; p2 = p2->Next(s2) ) {
				s2 = (p2->GetNode(1) == node);

				if ( !( p2->GetFlags() & FACE_FLOOR ) ) {
					continue;
				}

				if ( p2->GetFlags() & FACE_CHECKED ) {
					continue;
				}

				w2 = p2->GetWinding();

				min = 2.0f * GRAVSUBDIV_EPSILON;
				max = GRAVSUBDIV_EPSILON;
				if ( side1 == SIDE_FRONT ) {
					for ( j = 0; j < w2->GetNumPoints(); j++ ) {
						d = plane.Distance( (*w2)[j].ToVec3() );
						if ( d >= GRAVSUBDIV_EPSILON ) {
							break;	// point at the same side of the plane as the gap
						}
						d = idMath::Fabs( d );
						if ( d < min ) {
							min = d;
						}
						if ( d > max ) {
							max = d;
						}
					}
				}
				else {
					for ( j = 0; j < w2->GetNumPoints(); j++ ) {
						d = plane.Distance( (*w2)[j].ToVec3() );
						if ( d <= -GRAVSUBDIV_EPSILON ) {
							break;	// point at the same side of the plane as the gap
						}
						d = idMath::Fabs( d );
						if ( d < min ) {
							min = d;
						}
						if ( d > max ) {
							max = d;
						}
					}
				}

				// a point of the floor portal was found to be at the same side of the plane as the gap
				if ( j < w2->GetNumPoints() ) {
					continue;
				}

				// if the floor portal touches the plane
				if ( min < GRAVSUBDIV_EPSILON && max > GRAVSUBDIV_EPSILON ) {
					planeList.FindPlane( plane, 0.00001f, 0.1f );
				}

				p2->SetFlag( FACE_CHECKED );
				numFloorChecked++;

			}
			if ( numFloorChecked == floor ) {
				break;
			}
		}

		for ( p2 = node->GetPortals(); p2; p2 = p2->Next(s2) ) {
			s2 = (p2->GetNode(1) == node);
			p2->RemoveFlag( FACE_CHECKED );
		}
	}

	// if the leaf node does not have both floor and gap portals
	if ( !( gap && floor) ) {
		if ( floor ) {
			node->SetFlag( AREA_FLOOR );
		}
		else if ( gap ) {
			node->SetFlag( AREA_GAP );
		}
		return;
	}

	// if no valid seperators found
	if ( planeList.Num() == 0 ) {
		// NOTE: this should never happend, if it does the leaf node has degenerate portals
		return;
	}

	splitterOrder = (int *) _alloca( planeList.Num() * sizeof( int ) );
	bestNumSplits = (int *) _alloca( planeList.Num() * sizeof( int ) );
	numSplitters = 0;

	// test all possible seperators and sort them from best to worst
	for ( i = 0; i < planeList.Num(); i += 2 ) {
		numSplits = 0;

		for ( p1 = node->GetPortals(); p1; p1 = p1->Next(s1) ) {
			s1 = (p1->GetNode(1) == node);
			if ( p1->GetWinding()->PlaneSide( planeList[i], 0.1f ) == SIDE_CROSS ) {
				numSplits++;
			}
		}

		for ( j = 0; j < numSplitters; j++ ) {
			if ( numSplits < bestNumSplits[j] ) {
				for ( k = numSplitters; k > j; k-- ) {
					bestNumSplits[k] = bestNumSplits[k-1];
					splitterOrder[k] = splitterOrder[k-1];
				}
				bestNumSplits[j] = numSplits;
				splitterOrder[j] = i;
				numSplitters++;
				break;
			}
		}
		if ( j >= numSplitters ) {
			bestNumSplits[j] = numSplits;
			splitterOrder[j] = i;
			numSplitters++;
		}
	}

	// try all seperators in order from best to worst
	for ( i = 0; i < numSplitters; i++ ) {
		if ( node->Split( planeList[splitterOrder[i]], -1 ) ) {
			// we found a seperator that works
			break;
		}
	}
	if ( i >= numSplitters) {
		return;
	}

	DisplayRealTimeString( "\r%6d", ++numGravitationalSubdivisions );

	// test children for further splits
	GravSubdivLeafNode( node->GetChild(0) );
	GravSubdivLeafNode( node->GetChild(1) );
}
Exemple #12
0
//-----------------------------------------------------------------------------
// Purpose: extracts the list of defines and includes used for this config
//-----------------------------------------------------------------------------
bool CVCProjConvert::ExtractIncludes( IXMLDOMElement *pDoc, CConfiguration & config )
{
	config.ResetDefines();
	config.ResetIncludes();
	
	if (!pDoc)
	{
		return false;
	}

#ifdef _WIN32
	CComPtr<IXMLDOMNodeList> pTools;
	pDoc->getElementsByTagName( _bstr_t("Tool"), &pTools);
	if (pTools)
	{
		long len = 0;
		pTools->get_length(&len);
		for ( int i=0; i<len; i++ )
		{
			CComPtr<IXMLDOMNode> pNode;
			pTools->get_item( i, &pNode );
			if (pNode)
			{
				CComQIPtr<IXMLDOMElement> pElem( pNode );
				CUtlSymbol toolName = GetXMLAttribValue( pElem, "Name" );
				if ( toolName == "VCCLCompilerTool" )
				{
					CUtlSymbol defines = GetXMLAttribValue( pElem, "PreprocessorDefinitions" );
					char *str = (char *)_alloca( Q_strlen( defines.String() ) + 1 );
					Assert( str );
					Q_strcpy( str, defines.String() );
					// now tokenize the string on the ";" char
					char *delim = strchr( str, ';' );
					char *curpos = str;
					while ( delim )
					{
						*delim = 0;
						delim++;
						if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" )  &&  
							 Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines
						{
							config.AddDefine( curpos );
						}
						curpos = delim;
						delim = strchr( delim, ';' );
					}
					if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" )  &&  
						 Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines
					{
						config.AddDefine( curpos );
					}

					CUtlSymbol includes = GetXMLAttribValue( pElem, "AdditionalIncludeDirectories" );
					char *str2 = (char *)_alloca( Q_strlen( includes.String() ) + 1 );
					Assert( str2 );
					Q_strcpy( str2, includes.String() );
					// now tokenize the string on the ";" char
					delim = strchr( str2, ',' );
					curpos = str2;
					while ( delim )
					{
						*delim = 0;
						delim++;
						config.AddInclude( curpos );
						curpos = delim;
						delim = strchr( delim, ',' );
					}
					config.AddInclude( curpos );
				}
			}
		}
	}
#elif _LINUX
	DOMNodeList *nodes= pDoc->getElementsByTagName( _bstr_t("Tool"));
	if (nodes)
	{
		int len = nodes->getLength();
		for ( int i=0; i<len; i++ )
		{
			DOMNode *node = nodes->item(i);
			if (node)
			{
				CUtlSymbol toolName = GetXMLAttribValue( node, "Name" );
				if ( toolName == "VCCLCompilerTool" )
				{
					CUtlSymbol defines = GetXMLAttribValue( node, "PreprocessorDefinitions" );
					char *str = (char *)_alloca( Q_strlen( defines.String() ) + 1 );
					Assert( str );
					Q_strcpy( str, defines.String() );
					// now tokenize the string on the ";" char
					char *delim = strchr( str, ';' );
					char *curpos = str;
					while ( delim )
					{
						*delim = 0;
						delim++;
						if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" )  &&  
							 Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines
						{
							config.AddDefine( curpos );
						}
						curpos = delim;
						delim = strchr( delim, ';' );
					}
					if ( Q_stricmp( curpos, "WIN32" ) && Q_stricmp( curpos, "_WIN32" )  &&  
						 Q_stricmp( curpos, "_WINDOWS") && Q_stricmp( curpos, "WINDOWS")) // don't add WIN32 defines
					{
						config.AddDefine( curpos );
					}

					CUtlSymbol includes = GetXMLAttribValue( node, "AdditionalIncludeDirectories" );
					char *str2 = (char *)_alloca( Q_strlen( includes.String() ) + 1 );
					Assert( str2 );
					Q_strcpy( str2, includes.String() );
					// now tokenize the string on the ";" char
					char token = ',';
					delim = strchr( str2, token );
					if ( !delim )
					{
						token = ';';
						delim = strchr( str2, token );
					}
					curpos = str2;
					while ( delim )
					{
						*delim = 0;
						delim++;
						Q_FixSlashes( curpos );
						Q_strlower( curpos );
						char fullPath[ MAX_PATH ];
						Q_snprintf( fullPath, sizeof(fullPath), "%s/%s", m_BaseDir.String(), curpos );
						Q_StripTrailingSlash( fullPath );
						config.AddInclude( fullPath );
						curpos = delim;
						delim = strchr( delim, token );
					}
					Q_FixSlashes( curpos );
					Q_strlower( curpos );
					char fullPath[ MAX_PATH ];
					Q_snprintf( fullPath, sizeof(fullPath), "%s/%s", m_BaseDir.String(), curpos );
					Q_StripTrailingSlash( fullPath );
					config.AddInclude( fullPath );
				}
			}
		}
	}

#endif
	return true;
}
Exemple #13
0
int japan_post(struct zint_symbol *symbol, unsigned char source[], int length)
{ /* Japanese Postal Code (Kasutama Barcode) */
	int error_number, h;
	char pattern[69];
	int writer, loopey, inter_posn, i, sum, check;
	char check_char;
	char inter[23];

#ifndef _MSC_VER
        char local_source[length + 1];
#else
        char* local_source = (char*)_alloca(length + 1);
#endif
	
	inter_posn = 0;
	error_number = 0;

	strcpy(local_source, (char*)source);
	for(i = 0; i < length; i++) {
		local_source[i] = source[i];
	}
	to_upper((unsigned char*)local_source);
	error_number = is_sane(SHKASUTSET, (unsigned char*)local_source, length);

	if(error_number == ERROR_INVALID_DATA) {
		strcpy(symbol->errtxt, "Invalid characters in data");
		return error_number;
	}
	memset(inter, 'd', 20);/* Pad character CC4 */
	inter[20] = '\0';

	i = 0;
	inter_posn = 0;
	do {
		if(((local_source[i] >= '0') && (local_source[i] <= '9')) || (local_source[i] == '-')) {
			inter[inter_posn] = local_source[i];
			inter_posn++;
		} else {
			if((local_source[i] >= 'A') && (local_source[i] <= 'J')) {
				inter[inter_posn] = 'a';
				inter[inter_posn + 1] = local_source[i] - 'A' + '0';
				inter_posn += 2;
			}
			if((local_source[i] >= 'K') && (local_source[i] <= 'T')) {
				inter[inter_posn] = 'b';
				inter[inter_posn + 1] = local_source[i] - 'K' + '0';
				inter_posn += 2;
			}
			if((local_source[i] >= 'U') && (local_source[i] <= 'Z')) {
				inter[inter_posn] = 'c';
				inter[inter_posn + 1] = local_source[i] - 'U' + '0';
				inter_posn += 2;
			}
		}
		i++;
	}while((i < length) && (inter_posn < 20));
	inter[20] = '\0';

	strcpy(pattern, "13"); /* Start */

	sum = 0;
	for(i = 0; i < 20; i++) {
		concat(pattern, JapanTable[posn(KASUTSET, inter[i])]);
		sum += posn(CHKASUTSET, inter[i]);
		/* printf("%c (%d)\n", inter[i], posn(CHKASUTSET, inter[i])); */
	}

	/* Calculate check digit */
	check = 19 - (sum % 19);
	if(check == 19) { check = 0; }
	if(check <= 9) { check_char = check + '0'; }
	if(check == 10) { check_char = '-'; }
	if(check >= 11) { check_char = (check - 11) + 'a'; }
	concat(pattern, JapanTable[posn(KASUTSET, check_char)]);
	/* printf("check %c (%d)\n", check_char, check); */

	concat(pattern, "31"); /* Stop */

	/* Resolve pattern to 4-state symbols */
	writer = 0;
	h = strlen(pattern);
	for(loopey = 0; loopey < h; loopey++)
	{
		if((pattern[loopey] == '2') || (pattern[loopey] == '1'))
		{
			set_module(symbol, 0, writer);
		}
		set_module(symbol, 1, writer);
		if((pattern[loopey] == '3') || (pattern[loopey] == '1'))
		{
			set_module(symbol, 2, writer);
		}
		writer += 2;
	}

	symbol->row_height[0] = 3;
	symbol->row_height[1] = 2;
	symbol->row_height[2] = 3;
	symbol->rows = 3;
	symbol->width = writer - 1;

	return error_number;
}
Exemple #14
0
// __nID == 0 then separator
HWND MtlCreateSimpleToolBarCtrl(
		HWND		hWndParent,
		int *		__firstID,
		int *		__lastID,
		UINT		nImageBmpID,
		UINT		nHotImageBmpID,
		int 		cx,
		int 		cy,
		COLORREF	clrMask,
		UINT		nFlags,
		DWORD		dwStyle,
		UINT		nID)
{
	int 	nCount	= int (__lastID - __firstID);
	if (nCount == 0)
		return NULL;

	CImageList	 imgs;
	MTLVERIFY( imgs.Create(cx, cy, nFlags | ILC_MASK, nCount, 1) );

	CBitmap 	 bmp;
	MTLVERIFY( bmp.LoadBitmap(nImageBmpID) );
	imgs.Add(bmp, clrMask);

	CImageList	 imgsHot;
	MTLVERIFY( imgsHot.Create(cx, cy, nFlags | ILC_MASK, nCount, 1) );

	CBitmap 	 bmpHot;
	MTLVERIFY( bmpHot.LoadBitmap(nHotImageBmpID) );
	imgsHot.Add(bmpHot, clrMask);

	TBBUTTON *	 pTBBtn  = (TBBUTTON *) _alloca( nCount * sizeof (TBBUTTON) );

	int 		 nBmp	 = 0;
	int 		 j		 = 0;

	for (; __firstID < __lastID; ++__firstID) {
		ATLASSERT(j < nCount);

		if (*__firstID != 0) {
			pTBBtn[j].iBitmap	= nBmp++;
			pTBBtn[j].idCommand = *__firstID;
			pTBBtn[j].fsState	= TBSTATE_ENABLED;
			pTBBtn[j].fsStyle	= TBSTYLE_BUTTON;
			pTBBtn[j].dwData	= 0;
			pTBBtn[j].iString	= 0;
		} else {
			pTBBtn[j].iBitmap	= 8;
			pTBBtn[j].idCommand = 0;
			pTBBtn[j].fsState	= 0;
			pTBBtn[j].fsStyle	= TBSTYLE_SEP;
			pTBBtn[j].dwData	= 0;
			pTBBtn[j].iString	= 0;
		}

		++j;
	}

	CToolBarCtrl toolbar = ::CreateWindowEx(
									0,
									TOOLBARCLASSNAME,
									NULL,
									dwStyle,
									0,
									0,
									100,
									100,
									hWndParent,
									(HMENU) LongToHandle(nID),
									_Module.GetModuleInstance(),
									NULL);

	toolbar.SetButtonStructSize( sizeof (TBBUTTON) );
	toolbar.AddButtons(nCount, pTBBtn);
	toolbar.SetImageList(imgs);
	toolbar.SetHotImageList(imgsHot);

	return toolbar.m_hWnd;
}
Exemple #15
0
STDMETHODIMP_(MEVENT) CDbxKyoto::AddEvent(MCONTACT contactID, DBEVENTINFO *dbei)
{
	if (dbei == NULL || dbei->cbSize != sizeof(DBEVENTINFO)) return 0;
	if (dbei->timestamp == 0) return 0;

	DBEvent dbe;
	dbe.dwSignature = DBEVENT_SIGNATURE;
	dbe.contactID = contactID; // store native or subcontact's id
	dbe.ofsModuleName = GetModuleNameOfs(dbei->szModule);
	dbe.timestamp = dbei->timestamp;
	dbe.flags = dbei->flags;
	dbe.wEventType = dbei->eventType;
	dbe.cbBlob = dbei->cbBlob;
	BYTE *pBlob = dbei->pBlob;

	MCONTACT contactNotifyID = contactID;
	DBCachedContact *cc, *ccSub = NULL;
	if ((cc = m_cache->GetCachedContact(contactID)) == NULL)
		return 0;

	if (cc->IsSub()) {
		ccSub = cc;
		if ((cc = m_cache->GetCachedContact(cc->parentID)) == NULL)
			return 0;

		// set default sub to the event's source
		if (!(dbei->flags & DBEF_SENT))
			db_mc_setDefault(cc->contactID, contactID, false);
		contactID = cc->contactID; // and add an event to a metahistory
		if (db_mc_isEnabled())
			contactNotifyID = contactID;
	}

	if (m_safetyMode)
		if (NotifyEventHooks(hEventFilterAddedEvent, contactNotifyID, (LPARAM)dbei))
			return NULL;

	mir_ptr<BYTE> pCryptBlob;
	if (m_bEncrypted) {
		size_t len;
		BYTE *pResult = m_crypto->encodeBuffer(pBlob, dbe.cbBlob, &len);
		if (pResult != NULL) {
			pCryptBlob = pBlob = pResult;
			dbe.cbBlob = (DWORD)len;
			dbe.flags |= DBEF_ENCRYPTED;
		}
	}
	DWORD dwEventId;
	{
		mir_cslock lck(m_csDbAccess);
		dwEventId = ++m_dwMaxEventId;

		BYTE *pDest = (BYTE*)_alloca(sizeof(DBEvent) + dbe.cbBlob);
		memcpy(pDest, &dbe, sizeof(DBEvent));
		memcpy(pDest + sizeof(DBEvent), pBlob, dbe.cbBlob);
		m_dbEvents.set((LPCSTR)&dwEventId, sizeof(int), (LPCSTR)pDest, sizeof(DBEvent) + dbe.cbBlob);

		// add a sorting key
		DBEventSortingKey key2 = { contactID, dbe.timestamp, dwEventId };
		m_dbEventsSort.set((LPCSTR)&key2, sizeof(key2), "", 1);

		cc->Advance(dwEventId, dbe);
		m_dbContacts.set((LPCSTR)&contactID, sizeof(int), (LPCSTR)&cc->dbc, sizeof(DBContact));

		// insert an event into a sub's history too
		if (ccSub != NULL) {
			key2.dwContactId = ccSub->contactID;
			m_dbEventsSort.set((LPCSTR)&key2, sizeof(key2), "", 1);

			ccSub->Advance(dwEventId, dbe);
			m_dbContacts.set((LPCSTR)&ccSub->contactID, sizeof(int), (LPCSTR)&ccSub->dbc, sizeof(DBContact));
		}
	}

	// Notify only in safe mode or on really new events
	if (m_safetyMode)
		NotifyEventHooks(hEventAddedEvent, contactNotifyID, dwEventId);

	return dwEventId;
}
Exemple #16
0
INT_PTR CALLBACK SendDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	TSendContactsData* wndData = (TSendContactsData*)GetWindowLongPtr(hwndDlg, DWLP_USER);

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(hInst, MAKEINTRESOURCE(IDI_CONTACTS)));
		SetAllContactChecks(GetDlgItem(hwndDlg, IDC_LIST), lParam);
		WindowList_Add(g_hSendWindowList, hwndDlg, lParam);
		wndData = new TSendContactsData(lParam);
		SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)wndData);
		// new dlg init 
		wndData->hIcons[0] = InitMButton(hwndDlg, IDC_ADD, SKINICON_OTHER_ADDCONTACT, LPGENT("Add Contact Permanently to List"));
		wndData->hIcons[1] = InitMButton(hwndDlg, IDC_DETAILS, SKINICON_OTHER_USERDETAILS, LPGENT("View User's Details"));
		wndData->hIcons[2] = InitMButton(hwndDlg, IDC_HISTORY, SKINICON_OTHER_HISTORY, LPGENT("View User's History"));
		wndData->hIcons[3] = InitMButton(hwndDlg, IDC_USERMENU, SKINICON_OTHER_DOWNARROW, LPGENT("User Menu"));

		SendMessage(hwndDlg, DM_UPDATETITLE, 0, 0);
		// new dialog init done
		return TRUE;

	case WM_SETFOCUS:
		SetFocus(GetDlgItem(hwndDlg, IDC_LIST));
		break;

	case WM_NOTIFY:
		if (((LPNMHDR)lParam)->idFrom == IDC_LIST) {
			switch (((LPNMHDR)lParam)->code) {
			case CLN_NEWCONTACT:
			case CLN_LISTREBUILT: // rebuild list
				if (wndData) SetAllContactChecks(GetDlgItem(hwndDlg, IDC_LIST), wndData->hContact);
			}
		}
		break;

	case WM_TIMER:
		if (wParam == TIMERID_MSGSEND) {
			KillTimer(hwndDlg, wParam);
			wndData->ShowErrorDlg(hwndDlg, "The contacts send timed out.", TRUE);
		}
		break;

	case DM_ERRORDECIDED:
		EnableWindow(hwndDlg, TRUE);
		wndData->hError = NULL;
		switch (wParam) {
		case MSGERROR_CANCEL:
			wndData->UnhookProtoAck();
			if (wndData->uacklist.Count) {
				for (int i = 0; i < wndData->uacklist.Count; i++)
					delete g_aAckData.Remove(wndData->uacklist.Items[i]); // remove our ackdata & release structure

				mir_free(wndData->uacklist.Items);
				wndData->uacklist.Items = NULL;
				wndData->uacklist.Count = 0;
			}
			EnableDlgItem(hwndDlg, IDOK, TRUE);
			EnableDlgItem(hwndDlg, IDC_LIST, TRUE);
			ShowWindow(hwndDlg, SW_SHOWNORMAL);
			SetFocus(GetDlgItem(hwndDlg, IDC_LIST));
			break;

		case MSGERROR_DONE:
			// contacts were delivered succesfully after timeout
			SetFocus(GetDlgItem(hwndDlg, IDC_LIST));
			wndData->UnhookProtoAck();
			break;

		case MSGERROR_RETRY:// resend timeouted packets
			for (int i = 0; i < wndData->uacklist.Count; i++) {
				TAckData *lla = g_aAckData.Remove(wndData->uacklist.Items[i]);
				HANDLE hProcc = (HANDLE)CallContactService(wndData->hContact, PSS_CONTACTS, MAKEWPARAM(0, lla->nContacts), (LPARAM)lla->aContacts);

				if (!hProcc) { // if fatal do not include
					wndData->uacklist.Remove(wndData->uacklist.Items[i]);
					delete lla; // release the structure
					continue;
				}
				else {
					// update process code
					wndData->uacklist.Items[i] = hProcc;
					g_aAckData.Add(hProcc, lla);
				}
			}// collect TAckData for our window, resend
			break;
		}
		break;

	case WM_COMMAND:
		if (!lParam && CallService(MS_CLIST_MENUPROCESSCOMMAND, MAKEWPARAM(LOWORD(wParam), MPCF_CONTACTMENU), (LPARAM)wndData->hContact))
			break;

		switch (LOWORD(wParam)) {
		case IDOK:
			if (IsWindowEnabled(GetDlgItem(hwndDlg, IDOK))) {
				MCONTACT hContact, hItem;
				wndData->ClearContacts(); // do not include contacts twice

				HWND hList = GetDlgItem(hwndDlg, IDC_LIST);
				hContact = FindFirstClistContact(hList, &hItem);
				while (hContact) {
					// build list of contacts to send
					if (SendMessage(hList, CLM_GETCHECKMARK, (WPARAM)hItem, 0))
						wndData->AddContact(hContact);

					hContact = FindNextClistContact(hList, hContact, &hItem);
				}
				/* send contacts */
				if (!wndData->SendContacts(hwndDlg))
					break;

				SetTimer(hwndDlg, TIMERID_MSGSEND, db_get_dw(NULL, "SRMsg", "MessageTimeout", TIMEOUT_MSGSEND), NULL);
			}
			break;

		case IDCANCEL:
			DestroyWindow(hwndDlg);
			break;

		case ID_SELECTALL:
			{
				// select all contacts
				HWND hwndList = GetDlgItem(hwndDlg, IDC_LIST);
				MCONTACT hItem, hContact = FindFirstClistContact(hwndList, &hItem);
				while (hContact) {
					SendMessage(hwndList, CLM_SETCHECKMARK, (WPARAM)hItem, 1);
					hContact = FindNextClistContact(hwndList, hContact, &hItem);
				}
			}
			break;
	
		case IDC_USERMENU:
			{
				RECT rc;
				GetWindowRect(GetDlgItem(hwndDlg, IDC_USERMENU), &rc);
				HMENU hMenu = Menu_BuildContactMenu(wndData->hContact);
				TrackPopupMenu(hMenu, 0, rc.left, rc.bottom, 0, hwndDlg, NULL);
				DestroyMenu(hMenu);
			}
			break;

		case IDC_HISTORY:
			CallService(MS_HISTORY_SHOWCONTACTHISTORY, (WPARAM)wndData->hContact, 0);
			break;

		case IDC_DETAILS:
			CallService(MS_USERINFO_SHOWDIALOG, (WPARAM)wndData->hContact, 0);
			break;

		case IDC_ADD:
			DialogAddContactExecute(hwndDlg, wndData->hContact);
			break;
		}
		break;

	case HM_EVENTSENT:
		{
			ACKDATA *ack = (ACKDATA*)lParam;
			if (ack->type != ACKTYPE_CONTACTS)
				break;

			TAckData *ackData = g_aAckData.Get(ack->hProcess);
			if (ackData == NULL)
				break;    // on unknown hprocc go away

			if (ackData->hContact != ack->hContact)
				break; // this is not ours, strange

			if (ack->result == ACKRESULT_FAILED) {
				// some process failed, show error dialog
				KillTimer(hwndDlg, TIMERID_MSGSEND);
				wndData->ShowErrorDlg(hwndDlg, (char *)ack->lParam, TRUE);
				// ackData get used in error handling, released there
				break;
			}

			DBEVENTINFO dbei = { sizeof(dbei) };
			dbei.szModule = GetContactProto(ackData->hContact);
			dbei.eventType = EVENTTYPE_CONTACTS;
			dbei.flags = DBEF_SENT | DBEF_UTF;
			dbei.timestamp = time(NULL);
			//make blob
			TCTSend* maSend = (TCTSend*)_alloca(ackData->nContacts*sizeof(TCTSend));
			memset(maSend, 0, (ackData->nContacts * sizeof(TCTSend)));
			dbei.cbBlob = 0;
			char* pBlob;
			int i;
			for (i = 0; i < ackData->nContacts; i++) {
				// prepare data & count size
				maSend[i].mcaNick = mir_utf8encodeT(pcli->pfnGetContactDisplayName(ackData->aContacts[i], 0));
				maSend[i].mcaUIN = mir_utf8encodeT(ptrT(GetContactUID(ackData->aContacts[i])));
				dbei.cbBlob += (DWORD)strlennull(maSend[i].mcaUIN) + (DWORD)strlennull((char*)maSend[i].mcaNick) + 2;
			}
			dbei.pBlob = (PBYTE)_alloca(dbei.cbBlob);
			for (i = 0, pBlob = (char*)dbei.pBlob; i < ackData->nContacts; i++) {
				strcpynull(pBlob, (char*)maSend[i].mcaNick);
				pBlob += strlennull(pBlob) + 1;
				strcpynull(pBlob, maSend[i].mcaUIN);
				pBlob += strlennull(pBlob) + 1;
			}
			db_event_add(ackData->hContact, &dbei);
			g_aAckData.Remove(ack->hProcess); // do not release here, still needed
			wndData->uacklist.Remove(ack->hProcess); // packet confirmed
			for (i = 0; i < ackData->nContacts; i++) {
				mir_free(maSend[i].mcaUIN);
				mir_free(maSend[i].mcaNick);
			}
			delete ackData; // all done, release structure
			if (!wndData->uacklist.Count) {
				SkinPlaySound("SentContacts");
				KillTimer(hwndDlg, TIMERID_MSGSEND);

				if (wndData->hError)
					SendMessage(wndData->hError, DM_ERRORDECIDED, MSGERROR_DONE, 0);

				SendMessage(hwndDlg, WM_CLOSE, 0, 0); // all packets confirmed, close the dialog
			}
		}
		break;
	
	case WM_MEASUREITEM:
		return Menu_MeasureItem((LPMEASUREITEMSTRUCT)lParam);

	case WM_DRAWITEM:
		DrawProtocolIcon(hwndDlg, lParam, wndData->hContact);
		return Menu_DrawItem((LPDRAWITEMSTRUCT)lParam);

	case DM_UPDATETITLE:
		UpdateDialogTitle(hwndDlg, wndData ? wndData->hContact : NULL, TranslateT("Send Contacts to"));
		if (wndData)
			UpdateDialogAddButton(hwndDlg, wndData->hContact);
		break;

	case WM_CLOSE:
		wndData->UnhookProtoAck();
		DestroyWindow(hwndDlg);
		break;

	case WM_DESTROY:
		WindowList_Remove(g_hSendWindowList, hwndDlg);
		delete wndData;
		break;
	}

	return FALSE;
}
int __cdecl __crtCompareStringW(
        LCID     Locale,
        DWORD    dwCmpFlags,
        LPCWSTR  lpString1,
        int      cchCount1,
        LPCWSTR  lpString2,
        int      cchCount2,
        int      code_page
        )
{
        static int f_use = 0;

        /*
         * Look for unstubbed 'preferred' flavor. Otherwise use available flavor.
         * Must actually call the function to ensure it's not a stub.
         */

        if (0 == f_use)
        {
            if (0 != CompareStringW(0, 0, L"\0", 1, L"\0", 1))
                f_use = USE_W;

            else if (0 != CompareStringA(0, 0, "\0", 1, "\0", 1))
                f_use = USE_A;

            else
                return 0;
        }

        /*
         * CompareString will compare past NULL. Must find NULL if in string
         * before cchCountn wide characters.
         */

        if (cchCount1 > 0)
            cchCount1= wcsncnt(lpString1, cchCount1);
        if (cchCount2 > 0)
            cchCount2= wcsncnt(lpString2, cchCount2);

        if (!cchCount1 || !cchCount2)
            return (cchCount1 - cchCount2 == 0) ? 2 :
                   (cchCount1 - cchCount2 < 0) ? 1 : 3;

        /* Use "W" version */

        if (USE_W == f_use)
        {
            return CompareStringW( Locale,
                                   dwCmpFlags,
                                   lpString1,
                                   cchCount1,
                                   lpString2,
                                   cchCount2 );
        }

        /* Use "A" version */

        if (USE_A == f_use)
        {
            int buff_size1;
            int buff_size2;
            unsigned char *buffer1;
            unsigned char *buffer2;

            /*
             * Use __lc_codepage for conversion if code_page not specified
             */

            if (0 == code_page)
                code_page = __lc_codepage;

            /*
             * Convert strings and return the requested information.
             */

            /* find out how big a buffer we need (includes NULL if any) */
            if ( 0 == (buff_size1 = WideCharToMultiByte( code_page,
                                                         WC_COMPOSITECHECK |
                                                            WC_SEPCHARS,
                                                         lpString1,
                                                         cchCount1,
                                                         NULL,
                                                         0,
                                                         NULL,
                                                         NULL )) )
                return 0;

            /* allocate enough space for chars */
            __try {
                buffer1 = (unsigned char *)_alloca( buff_size1 * sizeof(char) );
            }
            __except( EXCEPTION_EXECUTE_HANDLER ) {
                buffer1 = NULL;
            }

            if ( buffer1 == NULL )
                return 0;

            /* do the conversion */
            if ( 0 == WideCharToMultiByte( code_page,
                                           WC_COMPOSITECHECK | WC_SEPCHARS,
                                           lpString1,
                                           cchCount1,
                                           buffer1,
                                           buff_size1,
                                           NULL,
                                           NULL ) )
                return 0;

            /* find out how big a buffer we need (includes NULL if any) */
            if ( 0 == (buff_size2 = WideCharToMultiByte( code_page,
                                                         WC_COMPOSITECHECK |
                                                            WC_SEPCHARS,
                                                         lpString2,
                                                         cchCount2,
                                                         NULL,
                                                         0,
                                                         NULL,
                                                         NULL )) )
                return 0;

            /* allocate enough space for chars */
            __try {
                buffer2 = (unsigned char *)_alloca( buff_size2 * sizeof(char) );
            }
            __except( EXCEPTION_EXECUTE_HANDLER ) {
                buffer2 = NULL;
            }

            if ( buffer2 == NULL )
                return 0;

            /* do the conversion */
            if ( 0 == WideCharToMultiByte( code_page,
                                           WC_COMPOSITECHECK | WC_SEPCHARS,
                                           lpString2,
                                           cchCount2,
                                           buffer2,
                                           buff_size2,
                                           NULL,
                                           NULL ) )
                return 0;

            return CompareStringA( Locale,
                                   dwCmpFlags,
                                   buffer1,
                                   buff_size1,
                                   buffer2,
                                   buff_size2 );
        }
Exemple #18
0
void w32_glob(int *argc_ptr, char ***argv_ptr) {
    wchar_t *wtmp = GetCommandLineW();
    char *cur, *begparm = NULL, *endparm = NULL;
    char **argv = NULL, c;
    int argc = 0, in_sq = 0, in_dq = 0, need_glob = 0, allarglen = 0, linelen;

    linelen = wcslen(wtmp);
    cur = _alloca(linelen * 6 + 1);
    if(!WideCharToMultiByte(CP_UTF8, 0, wtmp, -1, cur, linelen * 6 + 1, NULL, NULL))
	cur = GetCommandLineA();

    do {
	c = *cur;
	switch(c) {
	    case '\0':
		endparm = cur;
		break;
	    case ' ':
		if(begparm && !(in_sq | in_dq))
		    endparm = cur;
		break;
	    case '\'':
		if(!in_dq) {
		    in_sq = !in_sq;
		    if(!in_sq)
			endparm = cur;
		}
		break;
	    case '"':
		if(!in_sq) {
		    in_dq = !in_dq;
		    if(!in_dq)
			endparm = cur;
		}
		break;
	    case '*':
	    case '?':
		if(!in_sq)
		    need_glob = 1;
	    default:
		if(!begparm) {
		    begparm = cur;
		    endparm = NULL;
		}
	}
	if (begparm && endparm) {
	    if(begparm < endparm) {
		char *path = malloc(endparm - begparm + 1), *quotes;
		int arglen = 0;

		memcpy(path, begparm, endparm - begparm);
		path[endparm - begparm] = '\0';
		quotes = path;
		while((quotes = strchr(quotes, '"')))
		    memmove(quotes, quotes + 1, (endparm - begparm) - (quotes - path));
		if(argc && need_glob) {
		    arglen = glob_add(path, &argc, &argv);
		    if(!arglen) {
			path = malloc(endparm - begparm + 1);
			memcpy(path, begparm, endparm - begparm);
			path[endparm - begparm] = '\0';
		    }
		}
		if(!arglen) {
		    argv = realloc(argv, sizeof(*argv) * (argc + 1));
		    argv[argc] = path;
		    argc++;
		    arglen = endparm - begparm;
		}
		allarglen += arglen;
	    }
	    need_glob = 0;
	    in_sq = 0;
	    in_dq = 0;
	    begparm = NULL;
	    endparm = NULL;
	}
	cur++;
    } while (c);
    if(argc) {
	int i, argvlen = sizeof(*argv) * (argc + 1), argclen = 0;
	argv = realloc(argv, argvlen + allarglen + argc);
	argv[argc] = NULL;
	for(i=0; i<argc; i++) {
	    int curlen = strlen(argv[i]) + 1;
	    char *curarg = (char *)argv + argvlen + argclen;
	    memcpy(curarg, argv[i], curlen);
	    argclen += curlen;
	    free(argv[i]);
	    argv[i] = curarg;
	}
    }
    *argc_ptr = argc;
    *argv_ptr = argv;
}
VOID EtpNetworkIconUpdateCallback(
    _In_ struct _PH_NF_ICON *Icon,
    _Out_ PVOID *NewIconOrBitmap,
    _Out_ PULONG Flags,
    _Out_ PPH_STRING *NewText,
    _In_opt_ PVOID Context
    )
{
    static PH_GRAPH_DRAW_INFO drawInfo =
    {
        16,
        16,
        PH_GRAPH_USE_LINE_2,
        2,
        RGB(0x00, 0x00, 0x00),

        16,
        NULL,
        NULL,
        0,
        0,
        0,
        0
    };
    ULONG maxDataCount;
    ULONG lineDataCount;
    PFLOAT lineData1;
    PFLOAT lineData2;
    FLOAT max;
    ULONG i;
    HBITMAP bitmap;
    PVOID bits;
    HDC hdc;
    HBITMAP oldBitmap;
    HANDLE maxNetworkProcessId;
    PPH_PROCESS_ITEM maxNetworkProcessItem;
    PH_FORMAT format[6];

    // Icon

    Icon->Pointers->BeginBitmap(&drawInfo.Width, &drawInfo.Height, &bitmap, &bits, &hdc, &oldBitmap);
    maxDataCount = drawInfo.Width / 2 + 1;
    lineData1 = _alloca(maxDataCount * sizeof(FLOAT));
    lineData2 = _alloca(maxDataCount * sizeof(FLOAT));

    lineDataCount = min(maxDataCount, EtNetworkReceiveHistory.Count);
    max = 1024 * 1024; // minimum scaling of 1 MB.

    for (i = 0; i < lineDataCount; i++)
    {
        lineData1[i] = (FLOAT)PhGetItemCircularBuffer_ULONG(&EtNetworkReceiveHistory, i);
        lineData2[i] = (FLOAT)PhGetItemCircularBuffer_ULONG(&EtNetworkSendHistory, i);

        if (max < lineData1[i] + lineData2[i])
            max = lineData1[i] + lineData2[i];
    }

    PhDivideSinglesBySingle(lineData1, max, lineDataCount);
    PhDivideSinglesBySingle(lineData2, max, lineDataCount);

    drawInfo.LineDataCount = lineDataCount;
    drawInfo.LineData1 = lineData1;
    drawInfo.LineData2 = lineData2;
    drawInfo.LineColor1 = PhGetIntegerSetting(L"ColorIoReadOther");
    drawInfo.LineColor2 = PhGetIntegerSetting(L"ColorIoWrite");
    drawInfo.LineBackColor1 = PhHalveColorBrightness(drawInfo.LineColor1);
    drawInfo.LineBackColor2 = PhHalveColorBrightness(drawInfo.LineColor2);

    if (bits)
        PhDrawGraphDirect(hdc, bits, &drawInfo);

    SelectObject(hdc, oldBitmap);
    *NewIconOrBitmap = bitmap;
    *Flags = PH_NF_UPDATE_IS_BITMAP;

    // Text

    if (EtMaxNetworkHistory.Count != 0)
        maxNetworkProcessId = UlongToHandle(PhGetItemCircularBuffer_ULONG(&EtMaxNetworkHistory, 0));
    else
        maxNetworkProcessId = NULL;

    if (maxNetworkProcessId)
        maxNetworkProcessItem = PhReferenceProcessItem(maxNetworkProcessId);
    else
        maxNetworkProcessItem = NULL;

    PhInitFormatS(&format[0], L"Network\nR: ");
    PhInitFormatSize(&format[1], EtNetworkReceiveDelta.Delta);
    PhInitFormatS(&format[2], L"\nS: ");
    PhInitFormatSize(&format[3], EtNetworkSendDelta.Delta);

    if (maxNetworkProcessItem)
    {
        PhInitFormatC(&format[4], '\n');
        PhInitFormatSR(&format[5], maxNetworkProcessItem->ProcessName->sr);
    }

    *NewText = PhFormat(format, maxNetworkProcessItem ? 6 : 4, 128);
    if (maxNetworkProcessItem) PhDereferenceObject(maxNetworkProcessItem);
}
Exemple #20
0
static int glob_add(char *path, int *argc, char ***argv) {
    char *tail = strchr(path, '*'), *tailqmark;
    char *dup1, *dup2, *dir, *base, *taildirsep, *tailwldsep;
    struct dirent *de;
    int baselen, taillen, dirlen, mergedir = 0, outlen = 0;
    int qmarklen = 0;
    DIR *d;

    if(strlen(path) > 4 && !memcmp(path, "\\\\?\\", 4))
	tailqmark = strchr(&path[4], '?');
    else
	tailqmark = strchr(path, '?');

    if(tailqmark && (!tail || tailqmark < tail))
	tail = tailqmark;

    if(!tail) {
	*argv = realloc(*argv, sizeof(**argv) * (*argc + 1));
	(*argv)[*argc] = path;
	(*argc)++;
	return strlen(path);
    }

    if(tail!=path && tail[-1] == '\\') {
	tail[-1] = '\0';
	mergedir = 1;
    }
    while(*tail) {
	if(*tail == '?') {
	    if(tail == tailqmark || qmarklen) 
		qmarklen++;
	    *tail = 0;
	} else if(*tail == '*') {
	    *tail = '\0';
	    qmarklen = 0;
	} else 
	    break;
	tail++;
    }
    taillen = strlen(tail);
    taildirsep = strchr(tail, '\\');
    if(taildirsep && taildirsep - tail == taillen - 1) {
	*taildirsep = '\0';
	taildirsep = NULL;
	taillen--;
    }
    if(!taildirsep)
	taildirsep = tail + taillen;

    tailwldsep = strchr(tail, '*');
    tailqmark = strchr(tail, '?');
    if(tailqmark && (!tailwldsep || tailqmark < tailwldsep))
	tailwldsep = tailqmark;
    if(!tailwldsep)
	tailwldsep = tail + taillen;

    baselen = strlen(path) + 1;
    dup1 = (char *)_alloca(baselen * 2);
    memcpy(dup1, path, baselen);
    dup2 = dup1 + baselen;
    memcpy(dup2, path, baselen);

    if(!mergedir) {
	dir = dirname(dup1);
	base = basename(dup2);
    } else {
	dir = dup1;
	base = dup2;
	*dup2 = '\0';
    }

    dirlen = strlen(dir);
    baselen = strlen(base);

    d = opendir(dir);
    while(d && (de = readdir(d))) {
	int namelen = strlen(de->d_name);
	char *newpath;

	if(!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
	if(namelen < baselen) continue;
	if(strncasecmp(base, de->d_name, baselen)) continue;
	if(de->d_type == DT_DIR && taildirsep < tailwldsep) {
	    int d_taillen = taildirsep - tail;
	    if(namelen < baselen + d_taillen) continue;
	    if(strncasecmp(tail, &de->d_name[namelen - d_taillen], d_taillen)) continue;
	    newpath = malloc(dirlen + namelen + taillen - d_taillen + 3);
	    sprintf(newpath, "%s\\%s\\%s", dir, de->d_name, &tail[d_taillen+1]);
	    outlen += glob_add(newpath, argc, argv);
	} else {
	    int d_taillen = tailwldsep - tail;
	    char *start;
	    if(namelen < baselen + d_taillen) continue;
	    if(qmarklen && baselen + qmarklen + d_taillen != namelen)	continue;
	    if(d_taillen == taillen) {
		start = &de->d_name[namelen - d_taillen];
		namelen = d_taillen;
	    } else {
		start = &de->d_name[baselen];
		namelen -= baselen;
	    }

	    for(; namelen >= d_taillen; start++, namelen--) {
		if(strncasecmp(start, tail, d_taillen)) continue;
		newpath = malloc(dirlen + (start - de->d_name) +  taillen + 2);
		sprintf(newpath, "%s\\", dir);
		memcpy(&newpath[dirlen + 1], de->d_name, start - de->d_name);
		strcpy(&newpath[dirlen + 1 + start - de->d_name], tail);
		outlen += glob_add(newpath, argc, argv);
	    }
	}
    }
    if(d) closedir(d);
    _freea(dup1);
    free(path);
    return outlen;
}
Exemple #21
0
BIO *BIO_new_file(const char *filename, const char *mode)
{
    BIO *ret;
    FILE *file = NULL;

#  if defined(_WIN32) && defined(CP_UTF8)
    int sz, len_0 = (int)strlen(filename) + 1;
    DWORD flags;

    /*
     * Basically there are three cases to cover: a) filename is
     * pure ASCII string; b) actual UTF-8 encoded string and
     * c) locale-ized string, i.e. one containing 8-bit
     * characters that are meaningful in current system locale.
     * If filename is pure ASCII or real UTF-8 encoded string,
     * MultiByteToWideChar succeeds and _wfopen works. If
     * filename is locale-ized string, chances are that
     * MultiByteToWideChar fails reporting
     * ERROR_NO_UNICODE_TRANSLATION, in which case we fall
     * back to fopen...
     */
    if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
                                  filename, len_0, NULL, 0)) > 0 ||
        (GetLastError() == ERROR_INVALID_FLAGS &&
         (sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
                                   filename, len_0, NULL, 0)) > 0)
        ) {
        WCHAR wmode[8];
        WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));

        if (MultiByteToWideChar(CP_UTF8, flags,
                                filename, len_0, wfilename, sz) &&
            MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
                                wmode, OSSL_NELEM(wmode)) &&
            (file = _wfopen(wfilename, wmode)) == NULL &&
            (errno == ENOENT || errno == EBADF)
            ) {
            /*
             * UTF-8 decode succeeded, but no file, filename
             * could still have been locale-ized...
             */
            file = fopen(filename, mode);
        }
    } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
        file = fopen(filename, mode);
    }
#  else
    file = fopen(filename, mode);
#  endif
    if (file == NULL) {
        SYSerr(SYS_F_FOPEN, get_last_sys_error());
        ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
        if (errno == ENOENT)
            BIOerr(BIO_F_BIO_NEW_FILE, BIO_R_NO_SUCH_FILE);
        else
            BIOerr(BIO_F_BIO_NEW_FILE, ERR_R_SYS_LIB);
        return (NULL);
    }
    if ((ret = BIO_new(BIO_s_file())) == NULL) {
        fclose(file);
        return (NULL);
    }

    BIO_clear_flags(ret, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
                                             * UPLINK */
    BIO_set_fp(ret, file, BIO_CLOSE);
    return (ret);
}
Exemple #22
0
static int
_g_win32_fill_statbuf_from_handle_info (const wchar_t              *filename,
                                        const wchar_t              *filename_target,
                                        BY_HANDLE_FILE_INFORMATION *handle_info,
                                        struct __stat64            *statbuf)
{
  wchar_t drive_letter_w = 0;
  size_t drive_letter_size = MB_CUR_MAX;
  char *drive_letter = _alloca (drive_letter_size);

  /* If filename (target or link) is absolute,
   * then use the drive letter from it as-is.
   */
  if (filename_target != NULL &&
      filename_target[0] != L'\0' &&
      filename_target[1] == L':')
    drive_letter_w = filename_target[0];
  else if (filename[0] != L'\0' &&
           filename[1] == L':')
    drive_letter_w = filename[0];

  if (drive_letter_w > 0 &&
      iswalpha (drive_letter_w) &&
      iswascii (drive_letter_w) &&
      wctomb (drive_letter, drive_letter_w) == 1)
    statbuf->st_dev = toupper (drive_letter[0]) - 'A'; /* 0 means A: drive */
  else
    /* Otherwise use the PWD drive.
     * Return value of 0 gives us 0 - 1 = -1,
     * which is the "no idea" value for st_dev.
     */
    statbuf->st_dev = _getdrive () - 1;

  statbuf->st_rdev = statbuf->st_dev;
  /* Theoretically, it's possible to set it for ext-FS. No idea how.
   * Meaningless for all filesystems that Windows normally uses.
   */
  statbuf->st_ino = 0;
  statbuf->st_mode = 0;

  if ((handle_info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
    statbuf->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
  else
    statbuf->st_mode |= S_IFREG;
  /* No idea what S_IFCHR means here. */
  /* S_IFIFO is not even mentioned in MSDN */
  /* S_IFBLK is also not mentioned */

  /* The aim here is to reproduce MS stat() behaviour,
   * even if it's braindead.
   */
  statbuf->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
  if ((handle_info->dwFileAttributes & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
    statbuf->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;

  if (!S_ISDIR (statbuf->st_mode))
    {
      const wchar_t *name;
      const wchar_t *dot = NULL;

      if (filename_target != NULL)
        name = filename_target;
      else
        name = filename;

      do
        {
          wchar_t *last_dot = wcschr (name, L'.');
          if (last_dot == NULL)
            break;
          dot = last_dot;
          name = &last_dot[1];
        }
      while (TRUE);

      if ((dot != NULL &&
          (wcsicmp (dot, L".exe") == 0 ||
           wcsicmp (dot, L".com") == 0 ||
           wcsicmp (dot, L".bat") == 0 ||
           wcsicmp (dot, L".cmd") == 0)))
        statbuf->st_mode |= S_IXUSR | S_IXGRP | S_IXOTH;
    }

  statbuf->st_nlink = handle_info->nNumberOfLinks;
  statbuf->st_uid = statbuf->st_gid = 0;
  statbuf->st_size = (((guint64) handle_info->nFileSizeHigh) << 32) | handle_info->nFileSizeLow;
  statbuf->st_ctime = _g_win32_filetime_to_unix_time (&handle_info->ftCreationTime);
  statbuf->st_mtime = _g_win32_filetime_to_unix_time (&handle_info->ftLastWriteTime);
  statbuf->st_atime = _g_win32_filetime_to_unix_time (&handle_info->ftLastAccessTime);

  return 0;
}
Exemple #23
0
int main( int argc, char *argv[] )
#endif
{
#ifdef WIN32
	if (IsDebuggerPresent())
	{
		// turn on floating-point exceptions
		unsigned int prev;
		_controlfp_s(&prev, 0, /*_EM_ZERODIVIDE|*/_EM_INVALID);

		// enable debug heap in a debug build
		_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF|_CRTDBG_CHECK_EVERY_1024_DF|_CRTDBG_CHECK_CRT_DF|_CRTDBG_LEAK_CHECK_DF );
		_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
		_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);

		// default to output debug
		DEBUGPRINT_OUTPUTDEBUG = true;
	}
#endif

	// read preferences
	ReadPreferences("preferences.xml");

#if !defined(USE_SDL) && defined(WIN32)
	int argc = 1;
	char *argv[64] = { NULL };
	int argsize = strlen(lpCmdLine) + 1;
	char *argdata = static_cast<char *>(_alloca(argsize));
	memcpy(argdata, lpCmdLine, argsize);
	{
		for (char *ptr = strtok(argdata, " \t"); ptr != NULL; ptr = strtok(NULL, " \t"))
		{
			argv[argc++] = ptr;
		}
	}
#endif

	// process command-line arguments
	for (int i = 1; i < argc; ++i)
	{
		// if the argument is a command...
		if (argv[i][0] == '-' || argv[i][0] == '/')
		{
			// get command hash
			unsigned int command = Hash(argv[i]+1);

			// scan for next command
			int count = 0;
			for (int j = i+1; j < argc; j++)
			{
				if (argv[j][0] == '-' || argv[j][0] == '/')
				{
					break;
				}
				++count;
			}

			ProcessCommand(command, argv+i+1, count);
			i += count;
		}
	}

	// initialize
	if( !Init() )
		return 1;    

	// run game state machine
	while (GameStateUpdate());

	// clean up
	Done();

	// done
	return 0;
}
/*
====================
idSurface_Polytope::SplitPolytope
====================
*/
int idSurface_Polytope::SplitPolytope( const idPlane &plane, const float epsilon, idSurface_Polytope **front, idSurface_Polytope **back ) const {
	int side, i, j, s, v0, v1, v2, edgeNum;
	idSurface *surface[2];
	idSurface_Polytope *polytopeSurfaces[2], *surf;
	int *onPlaneEdges[2];

	onPlaneEdges[0] = (int *) _alloca( indexes.Num() / 3 * sizeof( int ) );
	onPlaneEdges[1] = (int *) _alloca( indexes.Num() / 3 * sizeof( int ) );

	side = Split( plane, epsilon, &surface[0], &surface[1], onPlaneEdges[0], onPlaneEdges[1] );

	*front = polytopeSurfaces[0] = new (TAG_IDLIB_SURFACE) idSurface_Polytope;
	*back = polytopeSurfaces[1] = new (TAG_IDLIB_SURFACE) idSurface_Polytope;

	for ( s = 0; s < 2; s++ ) {
		if ( surface[s] ) {
			polytopeSurfaces[s] = new idSurface_Polytope( *surface[s] );
			delete surface[s];
			surface[s] = NULL;
		}
	}

	*front = polytopeSurfaces[0];
	*back = polytopeSurfaces[1];

	if ( side != SIDE_CROSS ) {
		return side;
	}

	// add triangles to close off the front and back polytope
	for ( s = 0; s < 2; s++ ) {

		surf = polytopeSurfaces[s];

		edgeNum = surf->edgeIndexes[onPlaneEdges[s][0]];
		v0 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITSET(edgeNum)];
		v1 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITNOTSET(edgeNum)];

		for ( i = 1; onPlaneEdges[s][i] >= 0; i++ ) {
			for ( j = i+1; onPlaneEdges[s][j] >= 0; j++ ) {
				edgeNum = surf->edgeIndexes[onPlaneEdges[s][j]];
				if ( v1 == surf->edges[abs(edgeNum)].verts[INT32_SIGNBITSET(edgeNum)] ) {
					v1 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITNOTSET(edgeNum)];
					SwapValues( onPlaneEdges[s][i], onPlaneEdges[s][j] );
					break;
				}
			}
		}

		for ( i = 2; onPlaneEdges[s][i] >= 0; i++ ) {
			edgeNum = surf->edgeIndexes[onPlaneEdges[s][i]];
			v1 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITNOTSET(edgeNum)];
			v2 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITSET(edgeNum)];
			surf->indexes.Append( v0 );
			surf->indexes.Append( v1 );
			surf->indexes.Append( v2 );
		}

		surf->GenerateEdgeIndexes();
	}

	return side;
}
/*
====================
GenerateMegaMipMaps
====================
*/
void	idMegaTexture::GenerateMegaMipMaps( megaTextureHeader_t *header, idFile *outFile ) {
	outFile->Flush();

	// out fileSystem doesn't allow read / write access...
	idFile	*inFile = fileSystem->OpenFileRead( outFile->GetName() );

	int	tileOffset = 1;
	int	width = header->tilesWide;
	int	height = header->tilesHigh;

	int		tileSize = header->tileSize * header->tileSize * 4;
	byte	*oldBlock = (byte *)_alloca( tileSize );
	byte	*newBlock = (byte *)_alloca( tileSize );

	while ( width > 1 || height > 1 ) {
		int	newHeight = (height+1) >> 1;
		if ( newHeight < 1 ) {
			newHeight = 1;
		}
		int	newWidth = (width+1) >> 1;
		if ( width < 1 ) {
			width = 1;
		}
		common->Printf( "generating %i x %i block mip level\n", newWidth, newHeight );

		int		tileNum;

		for ( int y = 0 ; y < newHeight ; y++ ) {
			common->Printf( "row %i\n", y );
			session->UpdateScreen();

			for ( int x = 0 ; x < newWidth ; x++ ) {
				// mip map four original blocks down into a single new block
				for ( int yy = 0 ; yy < 2 ; yy++ ) {
					for ( int xx = 0 ; xx< 2 ; xx++ ) {
						int	tx = x*2 + xx;
						int ty = y*2 + yy;

						if ( tx > width || ty > height ) {
							// off edge, zero fill
							memset( newBlock, 0, sizeof( newBlock ) );
						} else {
							tileNum = tileOffset + ty * width + tx;
							inFile->Seek( tileNum * tileSize, FS_SEEK_SET );
							inFile->Read( oldBlock, tileSize );
						}
						// mip map the new pixels
						for ( int yyy = 0 ; yyy < TILE_SIZE / 2 ; yyy++ ) {
							for ( int xxx = 0 ; xxx < TILE_SIZE / 2 ; xxx++ ) {
								byte *in = &oldBlock[ ( yyy * 2 * TILE_SIZE + xxx * 2 ) * 4 ];
								byte *out = &newBlock[ ( ( ( TILE_SIZE/2 * yy ) + yyy ) * TILE_SIZE + ( TILE_SIZE/2 * xx ) + xxx ) * 4 ];
								out[0] = ( in[0] + in[4] + in[0+TILE_SIZE*4] + in[4+TILE_SIZE*4] ) >> 2;
								out[1] = ( in[1] + in[5] + in[1+TILE_SIZE*4] + in[5+TILE_SIZE*4] ) >> 2;
								out[2] = ( in[2] + in[6] + in[2+TILE_SIZE*4] + in[6+TILE_SIZE*4] ) >> 2;
								out[3] = ( in[3] + in[7] + in[3+TILE_SIZE*4] + in[7+TILE_SIZE*4] ) >> 2;
							}
						}

						// write the block out
						tileNum = tileOffset + width * height + y * newWidth + x;
						outFile->Seek( tileNum * tileSize, FS_SEEK_SET );
						outFile->Write( newBlock, tileSize );

					}
				}
			}
		}
		tileOffset += width * height;
		width = newWidth;
		height = newHeight;
	}

	delete inFile;
}
Exemple #26
0
INT_PTR CALLBACK RecvDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	TRecvContactsData *wndData = (TRecvContactsData*)GetWindowLongPtr(hwndDlg, DWLP_USER);
	MCONTACT hContact;

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			CLISTEVENT *pcle = (CLISTEVENT*)lParam;
			WindowList_Add(ghRecvWindowList, hwndDlg, pcle->hContact);
			SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(hInst, MAKEINTRESOURCE(IDI_CONTACTS)));
			EnableDlgItem(hwndDlg, IDOK, FALSE);
			EnableDlgItem(hwndDlg, IDDETAILS, FALSE);
			wndData = new TRecvContactsData(pcle->hContact);
			SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)wndData);
			wndData->mhDbEvent = pcle->hDbEvent; /// initialized, pcle not needed anymore
			wndData->mhListIcon = ImageList_Create(GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON),ILC_COLORDDB|ILC_MASK, 0, 1);
			wndData->mhPopup = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTACTMENU));
			TranslateMenu(wndData->mhPopup);
			wndData->hHook = HookEventMessage(ME_PROTO_ACK, hwndDlg, HM_EVENTSENT);

			char *szProto =GetContactProto(wndData->mhContact);

			HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS);
			ListView_SetExtendedListViewStyle(hLV, LVS_EX_CHECKBOXES|LVS_EX_FULLROWSELECT);
			// add columns
			RecvListView_AddColumn(hLV, 120, _A2T((char*)CallProtoService(szProto, PS_GETCAPS, PFLAG_UNIQUEIDTEXT, 0)), 0);
			RecvListView_AddColumn(hLV, 100, TranslateT("Nick"),       1);
			RecvListView_AddColumn(hLV, 100, TranslateT("First Name"), 2);
			RecvListView_AddColumn(hLV, 100, TranslateT("Last Name"),  3);

			// fill in groups
			SendMessage(GetDlgItem(hwndDlg, IDC_ENABLEGROUPS), BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
			RebuildGroupCombo(hwndDlg);

			{ // fill listview with received contacts
				DBEVENTINFO dbe = {0};

				dbe.cbSize = sizeof(DBEVENTINFO);
				dbe.cbBlob = db_event_getBlobSize(wndData->mhDbEvent);
				if (dbe.cbBlob != -1)  // this marks an invalid hDbEvent - all smashed anyway...
					dbe.pBlob = (PBYTE)_alloca(dbe.cbBlob);
				db_event_get(wndData->mhDbEvent, &dbe);
				char* pcBlob = (char*)dbe.pBlob;
				char* pcEnd = (char*)dbe.pBlob + dbe.cbBlob;

				HICON hiProto = LoadContactProtoIcon(wndData->mhContact);
				ImageList_AddIcon(wndData->mhListIcon, hiProto);
				DestroyIcon(hiProto); // imagelist copied the resource
				ListView_SetImageList(hLV, wndData->mhListIcon, LVSIL_SMALL);
				LVITEM lvi = {0};
				lvi.iImage = 0;
				lvi.mask = LVIF_TEXT | LVIF_IMAGE;

				for (int nItem = 0; ; nItem++)
				{ // Nick
					int strsize = (int)strlennull(pcBlob);
					TReceivedItem* pItem = wndData->AddReceivedItem();

					if (dbe.flags & DBEF_UTF)
						pItem->mcaNick = mir_utf8decodeT(pcBlob); 
					else
						pItem->mcaNick = mir_a2t(pcBlob);
					pcBlob += strsize + 1;
					// UIN
					strsize = (int)strlennull(pcBlob);
					pItem->mcaUIN = mir_a2t(pcBlob);
					pcBlob += strsize + 1;
					// add to listview
					lvi.iItem = nItem;
					lvi.pszText = pItem->mcaUIN;
					ListView_InsertItem(hLV, &lvi); // with image
					ListView_SetItemText(hLV, nItem, 1, pItem->mcaNick);
					// check for end of contacts
					if (pcBlob >= pcEnd)
						break;
				}
			}
			// new dlg init
			wndData->hIcons[0] = InitMButton(hwndDlg, IDC_ADD, MAKEINTRESOURCEA(IDI_ADDCONTACT), LPGEN("Add Contact Permanently to List"));
			wndData->hIcons[1] = InitMButton(hwndDlg, IDC_DETAILS, MAKEINTRESOURCEA(IDI_USERDETAILS), LPGEN("View User's Details"));
			wndData->hIcons[2] = InitMButton(hwndDlg, IDC_HISTORY, MAKEINTRESOURCEA(IDI_HISTORY), LPGEN("View User's History"));
			wndData->hIcons[3] = InitMButton(hwndDlg, IDC_USERMENU, MAKEINTRESOURCEA(IDI_DOWNARROW), LPGEN("User Menu"));

			SendMessage(hwndDlg,DM_UPDATETITLE,0,0);
			// new dialog init done
			Utils_RestoreWindowPosition(hwndDlg, NULL, MODULENAME, "");
			return TRUE;
		}
	case WM_NOTIFY:
		if (((LPNMHDR)lParam)->idFrom == IDC_CONTACTS) {
			switch (((LPNMHDR)lParam)->code) {
			case NM_DBLCLK:
				{
					HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS);
					if (ListView_GetSelectedCount(hLV) != 1) break; // if not clicking on item, bye
					wndData->iPopupItem = ListView_GetNextItem(hLV, -1, LVNI_ALL|LVNI_SELECTED);
					if (wndData->iPopupItem == -1) break; // if no item selected no user details available
					return SendMessage(hwndDlg, WM_COMMAND, ID_POPUP_USERDETAILS, 0); // show user details
				}
			case LVN_ITEMCHANGED:
				{
					LPNMLISTVIEW pNMLV = (LPNMLISTVIEW)lParam;
					HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS); // optimisation, for FOR-Cycle
					bool bExistsCheckedItem = false;     // there must be no checked items to disable "Add" button

					if (ListView_GetCheckState(hLV, pNMLV->iItem))
					{ // the user has checked this item
						bExistsCheckedItem = true; // enable "Add" button
					}
					else
					{ // loop thru items and check if at least one is checked
						for (int i = 0; i < ListView_GetItemCount(hLV); i++)
							if (ListView_GetCheckState(hLV, i))
							{  // we found checked item, enable add, exit loop
								bExistsCheckedItem = true;
								break;
							}
					}
					EnableDlgItem(hwndDlg, IDOK, bExistsCheckedItem);
					EnableDlgItem(hwndDlg, IDDETAILS, ListView_GetSelectedCount(hLV) > 0);
					break;
				}
			}
		}
		break;

	case WM_COMMAND:
		{
			if (!lParam && CallService(MS_CLIST_MENUPROCESSCOMMAND, MAKEWPARAM(LOWORD(wParam), MPCF_CONTACTMENU), (LPARAM)wndData->mhContact))
				break;

			switch(LOWORD(wParam))
			{
			case IDOK:  // "Add Selected" button click
				{ // for each selected item, find its index in the hDbEvent
					// and after that add this item to the DB permanently
					HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS);
					HWND hGroupsCombo = GetDlgItem(hwndDlg, IDC_GROUPS);
					HWND hGroupsCheck = GetDlgItem(hwndDlg, IDC_ENABLEGROUPS);
					int curs = SendMessage(hGroupsCombo, CB_GETCURSEL, 0, 0);
					TCHAR* caGroup = NULL;
					int nGroupId = -1;
					if (curs != CB_ERR && IsWindowEnabled(hGroupsCheck) && SendMessage(hGroupsCheck, BM_GETCHECK, 0, 0))
					{ //got groups, get the one selected in combo
						TCHAR* caGroup = (TCHAR*)_alloca((SendMessage(hGroupsCombo, CB_GETLBTEXTLEN, curs, 0) + 1) * sizeof(TCHAR));
						SendMessage(hGroupsCombo, CB_GETLBTEXT, curs, (LPARAM)caGroup);
						nGroupId = SendMessage(hGroupsCombo, CB_GETITEMDATA, curs, 0);
					}

					for (int i = 0; i < ListView_GetItemCount(hLV); i++)
						if (ListView_GetCheckState(hLV, i)) {
							// found checked contact item, add it
							TCHAR *caUIN = ListView_GetItemTextEx(hLV, i, 0);
							for (int j = 0; j < wndData->cbReceived; j++)   // determine item index in packet
								if (!lstrcmp(wndData->maReceived[j]->mcaUIN, caUIN)) {
									char *szProto =GetContactProto(wndData->mhContact);
									hContact = (MCONTACT)CallProtoService(szProto, PS_ADDTOLISTBYEVENT, MAKEWPARAM(0, j), (LPARAM)wndData->mhDbEvent);
									if (hContact && caGroup) {
										// use newest group API if available
										if (ServiceExists(MS_CLIST_CONTACTCHANGEGROUP))
											CallService(MS_CLIST_CONTACTCHANGEGROUP, hContact, (LPARAM)nGroupId);
										else
											db_set_ts(hContact, "CList", "Group", caGroup);
									}
									break;
								}
							mir_free(caUIN);
						} // move to next item
					break;
				}                    
			case IDDETAILS:
				{ // for each selected item, find its index in the hDbEvent
					// and after that add this item to the DB
					// finally, request Details window for this hContact
					HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS);
					for (int i = 0; i < ListView_GetItemCount(hLV); i++)
						if (ListView_GetItemState(hLV, i, LVIS_SELECTED)) {
							hContact = CreateTemporaryContactForItem(hwndDlg, wndData, i);
							if (hContact)
								CallService(MS_USERINFO_SHOWDIALOG, hContact, 0);
						}
				}
				break;

			case IDCANCEL:
				SendMessage(hwndDlg, WM_CLOSE, 0, 0);
				break;

			case IDC_ENABLEGROUPS:
				EnableGroupCombo(hwndDlg);
				break;

			case IDC_GROUPS:
				// rebuild group list on popup
				if (HIWORD(wParam) == CBN_DROPDOWN)
					RebuildGroupCombo(hwndDlg);
				break;

			case ID_POPUP_ADDUSER:
				hContact = CreateTemporaryContactForItem(hwndDlg, wndData, wndData->iPopupItem);
				if (hContact)
					DialogAddContactExecute(hwndDlg, hContact);
				break;

			case ID_POPUP_USERDETAILS:
				hContact = CreateTemporaryContactForItem(hwndDlg, wndData, wndData->iPopupItem);
				if (hContact)
					CallService(MS_USERINFO_SHOWDIALOG, hContact, 0 );
				break;

			case ID_POPUP_SENDMESSAGE:
				hContact = CreateTemporaryContactForItem(hwndDlg, wndData, wndData->iPopupItem);
				if (hContact)
					CallService(MS_MSG_SENDMESSAGE, hContact, 0);
				break;   

			case IDC_USERMENU:
				{
					RECT rc;
					HMENU hMenu = (HMENU)CallService(MS_CLIST_MENUBUILDCONTACT, (WPARAM)wndData->mhContact, 0);
					GetWindowRect(GetDlgItem(hwndDlg,IDC_USERMENU), &rc);
					TrackPopupMenu(hMenu, 0, rc.left, rc.bottom, 0, hwndDlg, NULL);
					DestroyMenu(hMenu);
				}
				break;

			case IDC_HISTORY:
				CallService(MS_HISTORY_SHOWCONTACTHISTORY,(WPARAM)wndData->mhContact,0);
				break;

			case IDC_DETAILS:
				CallService(MS_USERINFO_SHOWDIALOG,(WPARAM)wndData->mhContact,0);
				break;

			case IDC_ADD:
				DialogAddContactExecute(hwndDlg, wndData->mhContact);
				break;
			}
		}
		break;

	case WM_CONTEXTMENU:
		{
			HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS);
			LVHITTESTINFO lvh;
			RECT rt;

			wndData->iPopupItem = -1;
			if ((HWND)wParam != hLV) break;  // if not our ListView go away
			lvh.pt.x = LOWORD(lParam);
			lvh.pt.y = HIWORD(lParam);
			if (GetWindowRect(hLV, &rt)==0) return FALSE; // ?? why this, some check ??
			ScreenToClient(hLV, &lvh.pt); // convert to ListView local coordinates
			int ci = ListView_HitTest(hLV, &lvh);
			if (ci==-1) break; // mouse is not over any item
			wndData->iPopupItem = ci;
			TrackPopupMenu(GetSubMenu(wndData->mhPopup, 0), TPM_LEFTALIGN|TPM_TOPALIGN, LOWORD(lParam), HIWORD(lParam), 0, hwndDlg, NULL);
		}
		break;

	case HM_EVENTSENT:
		{
			ACKDATA *ack = (ACKDATA*)lParam;
			if (ack->type != ACKTYPE_SEARCH) break;      // not search ack, go away
			if (ack->hProcess != wndData->rhSearch) break; //not our search, go away
			if (ack->result == ACKRESULT_DATA) {
				HWND hLV = GetDlgItem(hwndDlg, IDC_CONTACTS);
				PROTOSEARCHRESULT *psr = (PROTOSEARCHRESULT*)ack->lParam;
				LVFINDINFO fi;
				fi.flags = LVFI_STRING;
				fi.psz = wndData->haUin;
				int iLPos = ListView_FindItem(hLV, -1, &fi);
				if (iLPos == -1) iLPos = 0;
				if (lstrcmp(psr->nick, _T("")) && psr->nick)
					ListView_SetItemText(hLV, iLPos, 1, psr->nick);
				ListView_SetItemText(hLV, iLPos, 2, psr->firstName);
				ListView_SetItemText(hLV, iLPos, 3, psr->lastName);
				break;
			}
			mir_free(wndData->haUin);
		}
		break;
	
	case WM_CLOSE:  // user closed window, so destroy it
		WindowList_Remove(ghRecvWindowList, hwndDlg);
		DestroyWindow(hwndDlg);
		break;

	case WM_DESTROY: // last message received by this dialog, cleanup
		db_event_markRead(wndData->mhContact, wndData->mhDbEvent);
		Utils_SaveWindowPosition(hwndDlg, NULL, MODULENAME, "");
		ImageList_Destroy(wndData->mhListIcon);
		UnhookEvent(wndData->hHook);
		DestroyMenu(wndData->mhPopup);
		{
			for (int i = 0; i < SIZEOF(wndData->hIcons); i++)
				DestroyIcon(wndData->hIcons[i]);
		}
		delete wndData; // automatically calls destructor
		break;

	case WM_MEASUREITEM:
		return CallService(MS_CLIST_MENUMEASUREITEM, wParam, lParam);

	case WM_DRAWITEM:
		DrawProtocolIcon(hwndDlg, lParam, wndData->mhContact);
		return CallService(MS_CLIST_MENUDRAWITEM, wParam, lParam);

	case WM_SIZE:
		if (!IsIconic(hwndDlg)) {
			// make the dlg resizeable
			UTILRESIZEDIALOG urd = { sizeof(urd) };
			urd.hInstance = hInst;
			urd.hwndDlg = hwndDlg;
			urd.lpTemplate = MAKEINTRESOURCEA(IDD_RECEIVE);
			urd.pfnResizer = RecvDlg_Resize;
			CallService(MS_UTILS_RESIZEDIALOG, 0, (LPARAM) & urd);
		}
		break;

	case WM_GETMINMAXINFO:
		{
			MINMAXINFO* mmi=(MINMAXINFO*)lParam;
			mmi->ptMinTrackSize.x = 480+2*GetSystemMetrics(SM_CXSIZEFRAME);
			mmi->ptMinTrackSize.y = 130+2*GetSystemMetrics(SM_CYSIZEFRAME);
		}
		break;

	case DM_UPDATETITLE:
		UpdateDialogTitle(hwndDlg, wndData ? wndData->mhContact : NULL, LPGENT("Contacts from"));
		if (wndData)
			UpdateDialogAddButton(hwndDlg, wndData->mhContact);
		break;        
	}
	return FALSE;
}
Exemple #27
0
int __cdecl __crtLCMapStringA(
        LCID     Locale,
        DWORD    dwMapFlags,
        LPCSTR   lpSrcStr,
        int      cchSrc,
        LPSTR    lpDestStr,
        int      cchDest,
        int      code_page,
        BOOL     bError
        )
{
        static int f_use = 0;

        /*
         * Look for unstubbed 'preferred' flavor. Otherwise use available flavor.
         * Must actually call the function to ensure it's not a stub.
         * (Always try wide version first so WinNT can process codepage correctly.)
         */

        if (0 == f_use) {
            if (0 != LCMapStringW(0, LCMAP_LOWERCASE, L"\0", 1, NULL, 0))
                f_use = USE_W;
            else if (0 != LCMapStringA(0, LCMAP_LOWERCASE, "\0", 1, NULL, 0))
                f_use = USE_A;
            else
                return 0;
        }

        /*
         * LCMapString will map past NULL. Must find NULL if in string
         * before cchSrc characters.
         */
        if (cchSrc > 0)
            cchSrc = strncnt(lpSrcStr, cchSrc);

        /* Use "A" version */

        if (USE_A == f_use) {
            return LCMapStringA( Locale, dwMapFlags, lpSrcStr, cchSrc,
                                 lpDestStr, cchDest );
        }

        /* Use "W" version */

        if (USE_W == f_use)
        {
            int retval;
            int inbuff_size;
            int outbuff_size;
            wchar_t *inwbuffer;
            wchar_t *outwbuffer;

            /*
             * Convert string and return the requested information. Note that
             * we are converting to a wide string so there is not a
             * one-to-one correspondence between number of wide chars in the
             * input string and the number of *bytes* in the buffer. However,
             * there had *better be* a one-to-one correspondence between the
             * number of wide characters and the number of multibyte characters
             * or the resulting mapped string will be worthless to the user.
             */

            /*
             * Use __lc_codepage for conversion if code_page not specified
             */

            if (0 == code_page)
                code_page = __lc_codepage;

            /* find out how big a buffer we need (includes NULL if any) */
            if ( 0 == (inbuff_size =
                       MultiByteToWideChar( code_page,
                                            bError ? MB_PRECOMPOSED |
                                                MB_ERR_INVALID_CHARS :
                                                MB_PRECOMPOSED,
                                            lpSrcStr,
                                            cchSrc,
                                            NULL,
                                            0 )) )
                return 0;

            /* allocate enough space for wide chars */
            __try {
                inwbuffer = (wchar_t *)_alloca( inbuff_size * sizeof(wchar_t) );
            }
            __except(EXCEPTION_EXECUTE_HANDLER) {
                inwbuffer = NULL;
            }

            if ( inwbuffer == NULL )
                return 0;

            /* do the conversion */
            if ( 0 == MultiByteToWideChar( code_page,
                                           MB_PRECOMPOSED,
                                           lpSrcStr,
                                           cchSrc,
                                           inwbuffer,
                                           inbuff_size) )
                return 0;

            /* get size required for string mapping */
            if ( 0 == (retval = LCMapStringW( Locale,
                                              dwMapFlags,
                                              inwbuffer,
                                              inbuff_size,
                                              NULL,
                                              0 )) )
                return 0;

            if (dwMapFlags & LCMAP_SORTKEY) {
                /* retval is size in BYTES */

                if (0 != cchDest) {

                    if (retval > cchDest)
                        return 0;

                    /* do string mapping */
                    if ( 0 == LCMapStringW( Locale,
                                            dwMapFlags,
                                            inwbuffer,
                                            inbuff_size,
                                            (LPWSTR)lpDestStr,
                                            cchDest ) )
                        return 0;
                }
            }
            else {
                /* retval is size in wide chars */

                outbuff_size = retval;

                /* allocate enough space for wide chars (includes NULL if any) */
                __try {
                    outwbuffer = (wchar_t *)_alloca( outbuff_size * sizeof(wchar_t) );
                }
                __except(EXCEPTION_EXECUTE_HANDLER) {
                    outwbuffer = NULL;
                }

                if ( outwbuffer == NULL )
                    return 0;

                /* do string mapping */
                if ( 0 == LCMapStringW( Locale,
                                        dwMapFlags,
                                        inwbuffer,
                                        inbuff_size,
                                        outwbuffer,
                                        outbuff_size ) )
                    return 0;

                if (0 == cchDest) {
                    /* get size required */
                    if ( 0 == (retval =
                               WideCharToMultiByte( code_page,
                                                    WC_COMPOSITECHECK |
                                                        WC_SEPCHARS,
                                                    outwbuffer,
                                                    outbuff_size,
                                                    NULL,
                                                    0,
                                                    NULL,
                                                    NULL )) )
                        return 0;
                }
                else {
                    /* convert mapping */
                    if ( 0 == (retval =
                               WideCharToMultiByte( code_page,
                                                    WC_COMPOSITECHECK |
                                                        WC_SEPCHARS,
                                                    outwbuffer,
                                                    outbuff_size,
                                                    lpDestStr,
                                                    cchDest,
                                                    NULL,
                                                    NULL )) )
                        return 0;
                }
            }

            return retval;
        }
Exemple #28
0
/*
=====================
idRenderModelOverlay::CreateOverlay

This projects on both front and back sides to avoid seams
The material should be clamped, because entire triangles are added, some of which
may extend well past the 0.0 to 1.0 texture range
=====================
*/
void idRenderModelOverlay::CreateOverlay( const idRenderModel *model, const idPlane localTextureAxis[2], const idMaterial *mtr ) {
	int i, maxVerts, maxIndexes, surfNum;
	idRenderModelOverlay *overlay = NULL;

	// count up the maximum possible vertices and indexes per surface
	maxVerts = 0;
	maxIndexes = 0;
	for ( surfNum = 0; surfNum < model->NumSurfaces(); surfNum++ ) {
		const modelSurface_t *surf = model->Surface( surfNum );
		if ( surf->geometry->numVerts > maxVerts ) {
			maxVerts = surf->geometry->numVerts;
		}
		if ( surf->geometry->numIndexes > maxIndexes ) {
			maxIndexes = surf->geometry->numIndexes;
		}
	}

	// make temporary buffers for the building process
	overlayVertex_t	*overlayVerts = (overlayVertex_t *)_alloca( maxVerts * sizeof( *overlayVerts ) );
	glIndex_t *overlayIndexes = (glIndex_t *)_alloca16( maxIndexes * sizeof( *overlayIndexes ) );

	// pull out the triangles we need from the base surfaces
	for ( surfNum = 0; surfNum < model->NumBaseSurfaces(); surfNum++ ) {
		const modelSurface_t *surf = model->Surface( surfNum );
		float d;

		if ( !surf->geometry || !surf->shader ) {
			continue;
		}

		// some surfaces can explicitly disallow overlays
		if ( !surf->shader->AllowOverlays() ) {
			continue;
		}

		const srfTriangles_t *stri = surf->geometry;

		// try to cull the whole surface along the first texture axis
		d = stri->bounds.PlaneDistance( localTextureAxis[0] );
		if ( d < 0.0f || d > 1.0f ) {
			continue;
		}

		// try to cull the whole surface along the second texture axis
		d = stri->bounds.PlaneDistance( localTextureAxis[1] );
		if ( d < 0.0f || d > 1.0f ) {
			continue;
		}

		byte *cullBits = (byte *)_alloca16( stri->numVerts * sizeof( cullBits[0] ) );
		idVec2 *texCoords = (idVec2 *)_alloca16( stri->numVerts * sizeof( texCoords[0] ) );

		SIMDProcessor->OverlayPointCull( cullBits, texCoords, localTextureAxis, stri->verts, stri->numVerts );

		glIndex_t *vertexRemap = (glIndex_t *)_alloca16( sizeof( vertexRemap[0] ) * stri->numVerts );
		SIMDProcessor->Memset( vertexRemap, -1,  sizeof( vertexRemap[0] ) * stri->numVerts );

		// find triangles that need the overlay
		int numVerts = 0;
		int numIndexes = 0;
		int triNum = 0;
		for ( int index = 0; index < stri->numIndexes; index += 3, triNum++ ) {
			int v1 = stri->indexes[index+0];
			int	v2 = stri->indexes[index+1];
			int v3 = stri->indexes[index+2];

			// skip triangles completely off one side
			if ( cullBits[v1] & cullBits[v2] & cullBits[v3] ) {
				continue;
			}

			// we could do more precise triangle culling, like the light interaction does, if desired

			// keep this triangle
			for ( int vnum = 0; vnum < 3; vnum++ ) {
				int ind = stri->indexes[index+vnum];
				if ( vertexRemap[ind] == (glIndex_t)-1 ) {
					vertexRemap[ind] = numVerts;

					overlayVerts[numVerts].vertexNum = ind;
					overlayVerts[numVerts].st[0] = texCoords[ind][0];
					overlayVerts[numVerts].st[1] = texCoords[ind][1];

					numVerts++;
				}
				overlayIndexes[numIndexes++] = vertexRemap[ind];
			}
		}

		if ( !numIndexes ) {
			continue;
		}

		overlaySurface_t *s = (overlaySurface_t *) Mem_Alloc( sizeof( overlaySurface_t ) );
		s->surfaceNum = surfNum;
		s->surfaceId = surf->id;
		s->verts = (overlayVertex_t *)Mem_Alloc( numVerts * sizeof( s->verts[0] ) );
		memcpy( s->verts, overlayVerts, numVerts * sizeof( s->verts[0] ) );
		s->numVerts = numVerts;
		s->indexes = (glIndex_t *)Mem_Alloc( numIndexes * sizeof( s->indexes[0] ) );
		memcpy( s->indexes, overlayIndexes, numIndexes * sizeof( s->indexes[0] ) );
		s->numIndexes = numIndexes;

		for ( i = 0; i < materials.Num(); i++ ) {
			if ( materials[i]->material == mtr ) {
				break;
			}
		}
		if ( i < materials.Num() ) {
            materials[i]->surfaces.Append( s );
		} else {
			overlayMaterial_t *mat = new overlayMaterial_t;
			mat->material = mtr;
			mat->surfaces.Append( s );
			materials.Append( mat );
		}
	}

	// remove the oldest overlay surfaces if there are too many per material
	for ( i = 0; i < materials.Num(); i++ ) {
		while( materials[i]->surfaces.Num() > MAX_OVERLAY_SURFACES ) {
			FreeSurface( materials[i]->surfaces[0] );
			materials[i]->surfaces.RemoveIndex( 0 );
		}
	}
}
void CIcqProto::handleFileAck(PBYTE buf, WORD wLen, DWORD dwUin, DWORD dwCookie, WORD wStatus, char* pszText)
{
	char* pszFileName = NULL;
	DWORD dwFileSize;
	MCONTACT hCookieContact;
	WORD wPort;
	WORD wFilenameLength;
	filetransfer* ft;

	// Find the filetransfer that belongs to this response
	if (!FindCookie(dwCookie, &hCookieContact, (void**)&ft)) {
		NetLog_Direct("Error: Received unexpected file transfer request response");
		return;
	}

	FreeCookie(dwCookie);

	if (hCookieContact != HContactFromUIN(dwUin, NULL)) {
		NetLog_Direct("Error: UINs do not match in file transfer request response");
		return;
	}

	// If status != 0, a request has been denied
	if (wStatus != 0) {
		NetLog_Direct("File transfer denied by %u.", dwUin);
		ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DENIED, (HANDLE)ft, 0);

		FreeCookie(dwCookie);

		return;
	}

	if (wLen < 6) { // sanity check
		NetLog_Direct("Ignoring malformed file transfer request response");
		return;
	}

	// Port to connect to
	unpackWord(&buf, &wPort);
	ft->dwRemotePort = wPort;
	wLen -= 2;

	// Unknown
	buf += 2;
	wLen -= 2;

	// Filename
	unpackLEWord(&buf, &wFilenameLength);
	if (wFilenameLength > 0) {
		if (wFilenameLength > wLen - 2)
			wFilenameLength = wLen - 2;
		pszFileName = (char*)_alloca(wFilenameLength + 1);
		unpackString(&buf, pszFileName, wFilenameLength);
		pszFileName[wFilenameLength] = '\0';
	}
	wLen = wLen - 2 - wFilenameLength;

	if (wLen >= 4) { // Total filesize
		unpackLEDWord(&buf, &dwFileSize);
		wLen -= 4;
	}
	else
		dwFileSize = 0;

	NetLog_Direct("File transfer ack from %u, port %u, name %s, size %u", dwUin, ft->dwRemotePort, pszFileName, dwFileSize);

	ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, (HANDLE)ft, 0);

	OpenDirectConnection(ft->hContact, DIRECTCONN_FILE, ft);
}
int __cdecl __crtLCMapStringW(
        LCID     Locale,
        DWORD    dwMapFlags,
        LPCWSTR  lpSrcStr,
        int      cchSrc,
        LPWSTR   lpDestStr,
        int      cchDest,
        int      code_page
        )
{
        static int f_use = 0;

        /*
         * Look for unstubbed 'preferred' flavor. Otherwise use available flavor.
         * Must actually call the function to ensure it's not a stub.
         */

        if (0 == f_use) {
            if (0 != LCMapStringW(0, LCMAP_LOWERCASE, L"\0", 1, NULL, 0))
                f_use = USE_W;
            else if (0 != LCMapStringA(0, LCMAP_LOWERCASE, "\0", 1, NULL, 0))
                f_use = USE_A;
            else
                return 0;
        }

        /*
         * LCMapString will map past NULL. Must find NULL if in string
         * before cchSrc wide characters.
         */
        if (cchSrc > 0)
            cchSrc = wcsncnt(lpSrcStr, cchSrc);

        /* Use "W" version */

        if (USE_W == f_use) {
            return LCMapStringW( Locale, dwMapFlags, lpSrcStr, cchSrc,
                                 lpDestStr, cchDest );
        }

        /* Use "A" version */

        if (USE_A == f_use) {

            int retval;
            int inbuff_size;
            int outbuff_size;
            unsigned char *inbuffer;
            unsigned char *outbuffer;

            /*
             * Convert string and return the requested information. Note that
             * we are converting to a multibyte string so there is not a
             * one-to-one correspondence between number of wide chars in the
             * input string and the number of *bytes* in the buffer. However,
             * there had *better be* a one-to-one correspondence between the
             * number of wide characters and the number of multibyte characters
             * (enforced by WC_SEPCHARS) in the buffer or the resulting mapped
             * string will be worthless to the user.
             *
             */

            /*
             * Use __lc_codepage for conversion if code_page not specified
             */

            if (0 == code_page)
                code_page = __lc_codepage;

            /* find out how big a buffer we need (includes NULL if any) */
            if ( 0 == (inbuff_size = WideCharToMultiByte( code_page,
                                                          WC_COMPOSITECHECK |
                                                            WC_SEPCHARS,
                                                          lpSrcStr,
                                                          cchSrc,
                                                          NULL,
                                                          0,
                                                          NULL,
                                                          NULL )) )
                return 0;

            /* allocate enough space for chars */
            __try {
                inbuffer = (unsigned char *)_alloca( inbuff_size * sizeof(char) );
            }
            __except(EXCEPTION_EXECUTE_HANDLER) {
                inbuffer = NULL;
            }

            if ( inbuffer == NULL )
                return 0;

            /* do the conversion */
            if ( 0 ==  WideCharToMultiByte( code_page,
                                            WC_COMPOSITECHECK | WC_SEPCHARS,
                                            lpSrcStr,
                                            cchSrc,
                                            inbuffer,
                                            inbuff_size,
                                            NULL,
                                            NULL ) )
                return 0;

            /* get size required for string mapping */
            if ( 0 == (outbuff_size = LCMapStringA( Locale,
                                                    dwMapFlags,
                                                    inbuffer,
                                                    inbuff_size,
                                                    NULL,
                                                    0 )) )
                return 0;

            /* allocate enough space for chars and NULL */
            __try {
                outbuffer = (unsigned char *)_alloca( outbuff_size * sizeof(char) );
            }
            __except(EXCEPTION_EXECUTE_HANDLER) {
                outbuffer = NULL;
            }

            if ( outbuffer == NULL )
                return 0;

            /* do string mapping */
            if ( 0 == LCMapStringA( Locale,
                                    dwMapFlags,
                                    inbuffer,
                                    inbuff_size,
                                    outbuffer,
                                    outbuff_size ) )
                return 0;

            if (dwMapFlags & LCMAP_SORTKEY) {

                /* outbuff_size > cchDest is allowed */
                retval = outbuff_size;

                if (0 != cchDest)
                    /* SORTKEY returns BYTES, just copy */
                    strncpy( (char *)lpDestStr,
                             (char *)outbuffer,
                             cchDest < outbuff_size ? cchDest : outbuff_size );
            }
            else {
                if (0 == cchDest) {
                    /* get size required */
                    if ( 0 == (retval = MultiByteToWideChar( code_page,
                                                             MB_PRECOMPOSED,
                                                             outbuffer,
                                                             outbuff_size,
                                                             NULL,
                                                             0 )) )
                        return 0;
                }
                else {
                    /* convert mapping */
                    if ( 0 == (retval = MultiByteToWideChar( code_page,
                                                             MB_PRECOMPOSED,
                                                             outbuffer,
                                                             outbuff_size,
                                                             lpDestStr,
                                                             cchDest )) )
                        return 0;
                }
            }

            return retval;
        }