コード例 #1
0
void CSharedFilesCtrl::OnDrawItem( int item, wxDC* dc, const wxRect& rect, const wxRect& rectHL, bool highlighted )
{
	CKnownFile *file = reinterpret_cast<CKnownFile*>(GetItemData(item));
	wxASSERT( file );

	if ( highlighted ) {
		CMuleColour newcol(GetFocus() ? wxSYS_COLOUR_HIGHLIGHT : wxSYS_COLOUR_BTNSHADOW);
		dc->SetBackground(newcol.Blend(125).GetBrush());
		dc->SetTextForeground( CMuleColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
		// The second blending goes over the first one.
		dc->SetPen(newcol.Blend(65).GetPen());
	} else {
		dc->SetBackground( CMuleColour(wxSYS_COLOUR_LISTBOX).GetBrush() );
		dc->SetTextForeground(CMuleColour(wxSYS_COLOUR_WINDOWTEXT));
		dc->SetPen(*wxTRANSPARENT_PEN);
	}

	dc->SetBrush(dc->GetBackground());
	dc->DrawRectangle(rectHL);
	dc->SetPen(*wxTRANSPARENT_PEN);

	// Offset based on the height of the fonts
	const int textVOffset = ( rect.GetHeight() - dc->GetCharHeight() ) / 2;
	// Empty space to each side of a column
	const int SPARE_PIXELS_HORZ	= 4;

	// The leftmost position of the current column
	int columnLeft = 0;

	for ( int i = 0; i < GetColumnCount(); ++i ) {
		const int columnWidth = GetColumnWidth(i);

		if (columnWidth > 2*SPARE_PIXELS_HORZ) {
			wxRect columnRect(
				columnLeft + SPARE_PIXELS_HORZ, rect.y,
				columnWidth - 2 * SPARE_PIXELS_HORZ, rect.height);

			wxDCClipper clipper(*dc, columnRect);

			wxString textBuffer;
			switch ( i ) {
				case ID_SHARED_COL_NAME:
					textBuffer = file->GetFileName().GetPrintable();

					if (file->GetFileRating() || file->GetFileComment().Length()) {
						int image = Client_CommentOnly_Smiley;
						if (file->GetFileRating()) {
							image = Client_InvalidRating_Smiley + file->GetFileRating() - 1;
						}

						wxASSERT(image >= Client_InvalidRating_Smiley);
						wxASSERT(image <= Client_CommentOnly_Smiley);

						int imgWidth = 16;

						theApp->amuledlg->m_imagelist.Draw(image, *dc, columnRect.x,
								columnRect.y + 1, wxIMAGELIST_DRAW_TRANSPARENT);

						// Move the text to the right
						columnRect.x += (imgWidth + 4);
					}

					break;

				case ID_SHARED_COL_SIZE:
					textBuffer = CastItoXBytes(file->GetFileSize());
					break;

				case ID_SHARED_COL_TYPE:
					textBuffer = GetFiletypeByName(file->GetFileName());
					break;

				case ID_SHARED_COL_PRIO:
					textBuffer = PriorityToStr(file->GetUpPriority(), file->IsAutoUpPriority());
					break;

				case ID_SHARED_COL_ID:
					textBuffer = file->GetFileHash().Encode();
					break;

				case ID_SHARED_COL_REQ:
					textBuffer = CFormat(wxT("%u (%u)"))
							% file->statistic.GetRequests()
							% file->statistic.GetAllTimeRequests();
					break;

				case ID_SHARED_COL_AREQ:
					textBuffer = CFormat(wxT("%u (%u)"))
							% file->statistic.GetAccepts()
							% file->statistic.GetAllTimeAccepts();
					break;

				case ID_SHARED_COL_TRA:
					textBuffer = CastItoXBytes(file->statistic.GetTransferred())
						+ wxT(" (") + CastItoXBytes(file->statistic.GetAllTimeTransferred()) + wxT(")");
					break;

				case ID_SHARED_COL_RTIO:
					textBuffer = CFormat(wxT("%.2f")) %	((double)file->statistic.GetAllTimeTransferred() / file->GetFileSize());
					break;

				case ID_SHARED_COL_PART:
					if ( file->GetPartCount() ) {
						wxRect barRect(columnRect.x, columnRect. y + 1,
							columnRect.width, columnRect.height - 2);

						DrawAvailabilityBar(file, dc, barRect);
					}
					break;

				case ID_SHARED_COL_CMPL:
					if ( file->m_nCompleteSourcesCountLo == 0 ) {
						if ( file->m_nCompleteSourcesCountHi ) {
							textBuffer = CFormat(wxT("< %u")) % file->m_nCompleteSourcesCountHi;
						} else {
							textBuffer = wxT("0");
						}
					} else if (file->m_nCompleteSourcesCountLo == file->m_nCompleteSourcesCountHi) {
						textBuffer = CFormat(wxT("%u")) % file->m_nCompleteSourcesCountLo;
					} else {
						textBuffer = CFormat(wxT("%u - %u")) % file->m_nCompleteSourcesCountLo % file->m_nCompleteSourcesCountHi;
					}

					break;

				case ID_SHARED_COL_PATH:
					if ( file->IsPartFile() ) {
						textBuffer = _("[PartFile]");
					} else {
						textBuffer = file->GetFilePath().GetPrintable();
					}
			}

			if (!textBuffer.IsEmpty()) {
				dc->DrawText(textBuffer, columnRect.x, columnRect.y + textVOffset);
			}
		}

		// Move to the next column
		columnLeft += columnWidth;
	}
}
コード例 #2
0
int CAICHSyncThread::Run()
{
	if ( !theApp.emuledlg->IsRunning() )
		return 0;
	// we need to keep a lock on this file while the thread is running
	CSingleLock lockKnown2Met(&CAICHHashSet::m_mutKnown2File);
	lockKnown2Met.Lock();
	
	// we collect all masterhashs which we find in the known2.met and store them in a list
	CList<CAICHHash> liKnown2Hashs;
	CString fullpath=thePrefs.GetConfigDir();
	fullpath.Append(KNOWN2_MET_FILENAME);
	CSafeFile file;
	CFileException fexp;
	uint32 nLastVerifiedPos = 0;

	if (!file.Open(fullpath,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyNone, &fexp)){
		if (fexp.m_cause != CFileException::fileNotFound){
			CString strError(_T("Failed to load ") KNOWN2_MET_FILENAME _T(" file"));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(LOG_STATUSBAR, _T("%s"), strError);
		}
		return false;
	}
	try {
		//setvbuf(file.m_pStream, NULL, _IOFBF, 16384);
		uint32 nExistingSize = (UINT)file.GetLength();
		uint16 nHashCount;
		while (file.GetPosition() < nExistingSize){
			liKnown2Hashs.AddTail(CAICHHash(&file));
			nHashCount = file.ReadUInt16();
			if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){
				AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName());
			}
			// skip the rest of this hashset
			file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
			nLastVerifiedPos = (UINT)file.GetPosition();
		}
	}
	catch(CFileException* error){
		if (error->m_cause == CFileException::endOfFile){
			LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_BAD));
			// truncate the file to the size to the last verified valid pos
			try{
				file.SetLength(nLastVerifiedPos);
			}
			catch(CFileException* error2){
				error2->Delete();
			}
		}
		else{
			TCHAR buffer[MAX_CFEXP_ERRORMSG];
			error->GetErrorMessage(buffer, ARRSIZE(buffer));
			LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer);
		}
		error->Delete();
		return false;
	}
	
	// now we check that all files which are in the sharedfilelist have a corresponding hash in out list
	// those how don'T are added to the hashinglist
	CList<CAICHHash> liUsedHashs;	
	CSingleLock sharelock(&theApp.sharedfiles->m_mutWriteList);
	sharelock.Lock();

	for (uint32 i = 0; i < theApp.sharedfiles->GetCount(); i++){
		CKnownFile* pCurFile = theApp.sharedfiles->GetFileByIndex(i);
		if (pCurFile != NULL && !pCurFile->IsPartFile() ){
			if (theApp.emuledlg==NULL || !theApp.emuledlg->IsRunning()) // in case of shutdown while still hashing
				return 0;
			if (pCurFile->GetAICHHashset()->GetStatus() == AICH_HASHSETCOMPLETE){
				bool bFound = false;
				for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;)
				{
					CAICHHash current_hash = liKnown2Hashs.GetNext(pos);
					if (current_hash == pCurFile->GetAICHHashset()->GetMasterHash()){
						bFound = true;
						liUsedHashs.AddTail(current_hash);
						//theApp.QueueDebugLogLine(false, _T("%s - %s"), current_hash.GetString(), pCurFile->GetFileName());
#ifdef _DEBUG
						// in debugmode we load and verify all hashsets
						ASSERT( pCurFile->GetAICHHashset()->LoadHashSet() );
//			 			pCurFile->GetAICHHashset()->DbgTest();
						pCurFile->GetAICHHashset()->FreeHashSet();
#endif
						break;
					}
				}
				if (bFound) // hashset is available, everything fine with this file
					continue;
			}
			pCurFile->GetAICHHashset()->SetStatus(AICH_ERROR);
			m_liToHash.AddTail(pCurFile);
		}
	}
	sharelock.Unlock();

	// removed all unused AICH hashsets from known2.met
	if (!thePrefs.IsRememberingDownloadedFiles() && liUsedHashs.GetCount() != liKnown2Hashs.GetCount()){
		file.SeekToBegin();
		try {
			uint32 nExistingSize = (UINT)file.GetLength();
			uint16 nHashCount;
			ULONGLONG posWritePos = 0;
			ULONGLONG posReadPos = 0;
			uint32 nPurgeCount = 0;
			while (file.GetPosition() < nExistingSize){
				CAICHHash aichHash(&file);
				nHashCount = file.ReadUInt16();
				if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){
					AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName());
				}
				if (liUsedHashs.Find(aichHash) == NULL){
					// unused hashset skip the rest of this hashset
					file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
					nPurgeCount++;
				}
				else if(nPurgeCount == 0){
					// used Hashset, but it does not need to be moved as nothing changed yet
					file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
					posWritePos = file.GetPosition();
				}
				else{
					// used Hashset, move position in file
					BYTE* buffer = new BYTE[nHashCount*CAICHHash::GetHashSize()];
					file.Read(buffer, nHashCount*CAICHHash::GetHashSize());
					posReadPos = file.GetPosition();
					file.Seek(posWritePos, CFile::begin);
					file.Write(aichHash.GetRawHash(), CAICHHash::GetHashSize());
					file.WriteUInt16(nHashCount);
					file.Write(buffer, nHashCount*CAICHHash::GetHashSize());
					delete[] buffer;
					posWritePos = file.GetPosition();
					file.Seek(posReadPos, CFile::begin); 
				}
			}
			posReadPos = file.GetPosition();
			file.SetLength(posWritePos);
			theApp.QueueDebugLogLine(false, _T("Cleaned up known2.met, removed %u hashsets (%s)"), nPurgeCount, CastItoXBytes(posReadPos-posWritePos)); 

			file.Flush();
			file.Close();
		}
		catch(CFileException* error){
			if (error->m_cause == CFileException::endOfFile){
				// we just parsed this files some ms ago, should never happen here
				ASSERT( false );
			}
			else{
				TCHAR buffer[MAX_CFEXP_ERRORMSG];
				error->GetErrorMessage(buffer, ARRSIZE(buffer));
				LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer);
			}
			error->Delete();
			return false;
		}
	}
	lockKnown2Met.Unlock();
	// warn the user if he just upgraded
	if (thePrefs.IsFirstStart() && !m_liToHash.IsEmpty()){
		LogWarning(GetResString(IDS_AICH_WARNUSER));
	}	
	if (!m_liToHash.IsEmpty()){
		theApp.QueueLogLine(true, GetResString(IDS_AICH_SYNCTOTAL), m_liToHash.GetCount() );
		theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(m_liToHash.GetCount());
		// let first all normal hashing be done before starting out synchashing
		CSingleLock sLock1(&theApp.hashing_mut); // only one filehash at a time
		while (theApp.sharedfiles->GetHashingCount() != 0){
			Sleep(100);
		}
		sLock1.Lock();
		uint32 cDone = 0;
		for (POSITION pos = m_liToHash.GetHeadPosition();pos != 0; cDone++)
		{
			if (theApp.emuledlg==NULL || !theApp.emuledlg->IsRunning()){ // in case of shutdown while still hashing
				return 0;
			}
			theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(m_liToHash.GetCount()-cDone);
			if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL)
				theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount();
			CKnownFile* pCurFile = m_liToHash.GetNext(pos);
			// just to be sure that the file hasnt been deleted lately
			if (!(theApp.knownfiles->IsKnownFile(pCurFile) && theApp.sharedfiles->GetFileByID(pCurFile->GetFileHash())) )
				continue;
			theApp.QueueLogLine(false, GetResString(IDS_AICH_CALCFILE), pCurFile->GetFileName());
			if(!pCurFile->CreateAICHHashSetOnly())
				theApp.QueueDebugLogLine(false, _T("Failed to create AICH Hashset while sync. for file %s"), pCurFile->GetFileName());
		}

		theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(0);
		if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL)
			theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount();
		sLock1.Unlock();
	}

	theApp.QueueDebugLogLine(false, _T("AICHSyncThread finished"));
	return 0;
}
コード例 #3
0
void CSharedFilesCtrl::OnRightClick(wxListEvent& event)
{
	long item_hit = CheckSelection(event);

	if ( (m_menu == NULL) && (item_hit != -1)) {
		m_menu = new wxMenu(_("Shared Files"));
		wxMenu* prioMenu = new wxMenu();
		prioMenu->AppendCheckItem(MP_PRIOVERYLOW, _("Very low"));
		prioMenu->AppendCheckItem(MP_PRIOLOW, _("Low"));
		prioMenu->AppendCheckItem(MP_PRIONORMAL, _("Normal"));
		prioMenu->AppendCheckItem(MP_PRIOHIGH, _("High"));
		prioMenu->AppendCheckItem(MP_PRIOVERYHIGH, _("Very High"));
		prioMenu->AppendCheckItem(MP_POWERSHARE, _("Release"));
		prioMenu->AppendCheckItem(MP_PRIOAUTO, _("Auto"));

		m_menu->Append(0,_("Priority"),prioMenu);
		m_menu->AppendSeparator();

		CKnownFile* file = reinterpret_cast<CKnownFile*>(GetItemData(item_hit));
		if (file->GetFileComment().IsEmpty() && !file->GetFileRating()) {
			m_menu->Append(MP_CMT, _("Add Comment/Rating"));
		} else {
			m_menu->Append(MP_CMT, _("Edit Comment/Rating"));
		}

		m_menu->AppendSeparator();
		m_menu->Append(MP_RENAME, _("Rename"));
		m_menu->AppendSeparator();

		if (file->GetFileName().GetExt() == wxT("emulecollection")) {
			m_menu->Append( MP_ADDCOLLECTION, _("Add files in collection to transfer list"));
			m_menu->AppendSeparator();
		}
		m_menu->Append(MP_GETMAGNETLINK,_("Copy magnet &URI to clipboard"));
		m_menu->Append(MP_GETED2KLINK,_("Copy eD2k &link to clipboard"));
		m_menu->Append(MP_GETSOURCEED2KLINK,_("Copy eD2k link to clipboard (&Source)"));
		m_menu->Append(MP_GETCRYPTSOURCEDED2KLINK,_("Copy eD2k link to clipboard (Source) (&With Crypt options)"));
		m_menu->Append(MP_GETHOSTNAMESOURCEED2KLINK,_("Copy eD2k link to clipboard (&Hostname)"));
		m_menu->Append(MP_GETHOSTNAMECRYPTSOURCEED2KLINK,_("Copy eD2k link to clipboard (Hostname) (With &Crypt options)"));
		m_menu->Append(MP_GETAICHED2KLINK,_("Copy eD2k link to clipboard (&AICH info)"));
		m_menu->Append(MP_GETAICHED2KLINKSRC,_("Copy eD2k link to clipboard (&AICH info + Source)"));
		m_menu->Append(MP_WS,_("Copy feedback to clipboard"));

		m_menu->Enable(MP_GETAICHED2KLINK, file->HasProperAICHHashSet());
		m_menu->Enable(MP_GETAICHED2KLINKSRC, file->HasProperAICHHashSet());
		m_menu->Enable(MP_GETHOSTNAMESOURCEED2KLINK, !thePrefs::GetYourHostname().IsEmpty());
		m_menu->Enable(MP_GETHOSTNAMECRYPTSOURCEED2KLINK, !thePrefs::GetYourHostname().IsEmpty());

		int priority = file->IsAutoUpPriority() ? PR_AUTO : file->GetUpPriority();

		prioMenu->Check(MP_PRIOVERYLOW,	priority == PR_VERYLOW);
		prioMenu->Check(MP_PRIOLOW,	priority == PR_LOW);
		prioMenu->Check(MP_PRIONORMAL,	priority == PR_NORMAL);
		prioMenu->Check(MP_PRIOHIGH,	priority == PR_HIGH);
		prioMenu->Check(MP_PRIOVERYHIGH,priority == PR_VERYHIGH);
		prioMenu->Check(MP_POWERSHARE,	priority == PR_POWERSHARE);
		prioMenu->Check(MP_PRIOAUTO,	priority == PR_AUTO);

		PopupMenu( m_menu, event.GetPoint() );

		delete m_menu;

		m_menu = NULL;
	}
}
コード例 #4
0
void CQueueListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
#define LIST_CELL_PADDING	6		//should be even number
	if (!g_App.m_pMDlg->IsRunning() || !lpDrawItemStruct->itemData)
		return;

	CDC		*odc = CDC::FromHandle(lpDrawItemStruct->hDC);
	BOOL	bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS));
	COLORREF	crBk, crWinBk;

	crWinBk = crBk = GetBkColor();
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
		crBk = (bCtrlFocused) ? m_crHighlight : m_crNoHighlight;

	CUpDownClient	*pClient = reinterpret_cast<CUpDownClient*>(lpDrawItemStruct->itemData);
	CMemDC			dc(odc, &lpDrawItemStruct->rcItem, crWinBk, crBk);
	CFont			*pOldFont = dc.SelectObject(GetFont());
	COLORREF		crOldTextColor = dc->SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
	int				iWidth, iColumn;
	bool			bMeasuring = (m_iMeasuringColumn >= 0);
	UINT			iCalcFlag = bMeasuring ? (DT_LEFT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_NOCLIP|DT_CALCRECT) : (DT_LEFT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_NOCLIP|DT_END_ELLIPSIS);

	if (IsRightToLeftLanguage())
		iCalcFlag |= DT_RTLREADING;

	RECT			r = lpDrawItemStruct->rcItem;
	CString			strBuffer;

	CKnownFile		*pKnownFile = g_App.m_pSharedFilesList->GetFileByID(pClient->m_reqFileHash);
	CHeaderCtrl		*pHeaderCtrl = GetHeaderCtrl();
	int				iNumColumns = pHeaderCtrl->GetItemCount();

	r.right = r.left - LIST_CELL_PADDING / 2;
	r.left += LIST_CELL_PADDING / 2;
	iWidth = LIST_CELL_PADDING;

	for (int iCurrent = 0; iCurrent < iNumColumns; iCurrent++)
	{
		iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
		if (IsColumnHidden(iColumn) || (bMeasuring && iColumn != m_iMeasuringColumn))
			continue;

		r.right += CListCtrl::GetColumnWidth(iColumn);
		switch (iColumn)
		{
			case QLCOL_USERNAME:
			{
				if (!bMeasuring)
				{
					POINT		point = {r.left, r.top + 1};
					int			iImgLstIdx = CLIENT_IMGLST_PLAIN;

				//	Select corresponding image list depending on client properties
					if (pClient->IsBanned())
						iImgLstIdx = CLIENT_IMGLST_BANNED;
					else if (pClient->IsFriend())
						iImgLstIdx = CLIENT_IMGLST_FRIEND;
					else if (pClient->m_pCredits->HasHigherScoreRatio(pClient->GetIP()))
						iImgLstIdx = CLIENT_IMGLST_CREDITUP;

				//	Display Client icon
					g_App.m_pMDlg->m_clientImgLists[iImgLstIdx].Draw(dc, pClient->GetClientIconIndex(), point, ILD_NORMAL);

					r.left += 20;
					if (g_App.m_pIP2Country->ShowCountryFlag())
					{
						point.x += 20;
						point.y += 2;
						g_App.m_pIP2Country->GetFlagImageList()->Draw(dc, pClient->GetCountryIndex(), point, ILD_NORMAL);
						r.left += 22;
					}
				}
				else
				{
					iWidth += 20;
					if (g_App.m_pIP2Country->ShowCountryFlag())
						iWidth += 22;
				}

				strBuffer = pClient->GetUserName();
				break;
			}
			case QLCOL_FILENAME:
				if (pKnownFile)
					strBuffer = pKnownFile->GetFileName();
				else
					strBuffer = _T("?");
				break;

			case QLCOL_FILEPRIORITY:
			{
				if (pKnownFile)
				{
					UINT		dwResStrId;

					switch (pKnownFile->GetULPriority())
					{
						case PR_RELEASE:
							dwResStrId = IDS_PRIORELEASE;
							break;
						case PR_HIGH:
							dwResStrId = IDS_PRIOHIGH;
							break;
						case PR_LOW:
							dwResStrId = IDS_PRIOLOW;
							break;
						case PR_VERYLOW:
							dwResStrId = IDS_PRIOVERYLOW;
							break;
						default:
							dwResStrId = IDS_PRIONORMAL;
							break;
					}
					GetResString(&strBuffer, dwResStrId);
				}
				else
					strBuffer = _T("?");
				break;
			}
			case QLCOL_PARTS:
				if (pClient->GetUpPartCount())
					strBuffer.Format(_T("%u/%u"), pClient->GetAvailUpPartCount(), pClient->GetUpPartCount());
				else
					strBuffer = _T("");
				break;

			case QLCOL_PROGRESS:
			{
				if (pClient->GetUpPartCount() && g_App.m_pPrefs->IsUploadPartsEnabled())
				{
					if (!bMeasuring)
					{
						RECT	r2;

						r2.bottom = r.bottom - 1;
						r2.top = r.top + 1;
						r2.right = r.right + LIST_CELL_PADDING / 2;
						r2.left = r.left - LIST_CELL_PADDING / 2;
						pClient->DrawUpStatusBar(dc, &r2, g_App.m_pPrefs->UseFlatBar());
					}
					iWidth = 300;
				}
				break;
			}
			case QLCOL_QLRATING:
				strBuffer.Format(_T("%u"), pClient->GetScore(true));
				break;

			case QLCOL_SCORE:
			//	Note: actually the client, which is downloading from us should be not in WaitingQueue
				if (pClient->IsDownloading())
					strBuffer = _T("-");
				else
					strBuffer.Format((pClient->IsAddNextConnect()) ? _T("%u*") : _T("%u"), pClient->GetScore());
				break;

			case QLCOL_SFRATIO:
				if (pKnownFile != NULL)
					strBuffer.Format(_T("%.2f"), pKnownFile->GetSizeRatio());
				else
					strBuffer = _T("-");
				break;

			case QLCOL_RFRATIO:
				if (pKnownFile != NULL)
					strBuffer.Format(_T("%.2f"), pKnownFile->GetPopularityRatio());
				else
					strBuffer = _T("-");
				break;

			case QLCOL_TIMESASKED:
				strBuffer.Format(_T("%u"), pClient->GetAskedCount());
				break;

			case QLCOL_LASTSEEN:
				strBuffer = CastSecondsToHM((GetTickCount() - pClient->GetLastUpRequest())/1000);
				break;

			case QLCOL_ENTEREDQUEUE:
				strBuffer = CastSecondsToHM((GetTickCount() - pClient->GetWaitStartTime())/1000);
				break;

			case QLCOL_BANNED:
				strBuffer = YesNoStr(pClient->IsBanned());
				break;

			case QLCOL_COUNTRY:
				strBuffer = pClient->GetCountryName();
				break;
		}
		if (iColumn != QLCOL_PROGRESS)
		{
			dc->DrawText(strBuffer, &r, iCalcFlag);
			if (bMeasuring && !strBuffer.IsEmpty())
				iWidth += r.right - r.left + 1;
		}
		r.left = r.right + LIST_CELL_PADDING;

		if (bMeasuring)
		{
		//	Pin the column widths at some reasonable value
			if (iWidth < 40)
				iWidth = 40;
			if (iWidth > m_iColumnMaxWidths[m_iMeasuringColumn])
				m_iColumnMaxWidths[m_iMeasuringColumn] = iWidth;
		}
	}
//	Draw rectangle around selected item(s)
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
	{
		RECT	rOutline = lpDrawItemStruct->rcItem;
		CBrush	FrmBrush((bCtrlFocused) ? m_crFocusLine : m_crNoFocusLine);

		rOutline.left++;
		rOutline.right--;
		dc->FrameRect(&rOutline, &FrmBrush);
	}
	if (pOldFont)
		dc.SelectObject(pOldFont);
	if (crOldTextColor)
		dc.SetTextColor(crOldTextColor);
#undef LIST_CELL_PADDING
}
コード例 #5
0
BOOL CClientDetailDialog::OnInitDialog(){
	CDialog::OnInitDialog();
	InitWindowStyles(this);
	Localize();
	CString buffer;
	if (m_client->GetUserName())
		GetDlgItem(IDC_DNAME)->SetWindowText(m_client->GetUserName());
	else
		GetDlgItem(IDC_DNAME)->SetWindowText(_T("?"));
	
	if (m_client->HasValidHash()){
		buffer = _T("");
		CString buffer2;
		for (uint16 i = 0;i != 16;i++){
			buffer2.Format(_T("%02X"),m_client->GetUserHash()[i]);
			buffer+=buffer2;
		}
		GetDlgItem(IDC_DHASH)->SetWindowText(buffer);
	}
	else
		GetDlgItem(IDC_DHASH)->SetWindowText(_T("?"));
	
	GetDlgItem(IDC_DSOFT)->SetWindowText(m_client->GetClientSoftVer());

	buffer.Format(_T("%s"),(m_client->HasLowID() ? GetResString(IDS_IDLOW):GetResString(IDS_IDHIGH)));
	GetDlgItem(IDC_DID)->SetWindowText(buffer);
	
	if (m_client->GetServerIP()){
		CString strServerIP = ipstr(m_client->GetServerIP());
		GetDlgItem(IDC_DSIP)->SetWindowText(strServerIP);
		
		CServer* cserver = theApp.serverlist->GetServerByAddress(strServerIP, m_client->GetServerPort()); 
		if (cserver)
			GetDlgItem(IDC_DSNAME)->SetWindowText(cserver->GetListName());
		else
			GetDlgItem(IDC_DSNAME)->SetWindowText(_T("?"));
	}
	else{
		GetDlgItem(IDC_DSIP)->SetWindowText(_T("?"));
		GetDlgItem(IDC_DSNAME)->SetWindowText(_T("?"));
	}

	CKnownFile* file = theApp.sharedfiles->GetFileByID(m_client->GetUploadFileID());
	if (file)
		GetDlgItem(IDC_DDOWNLOADING)->SetWindowText(file->GetFileName() );
	else
		GetDlgItem(IDC_DDOWNLOADING)->SetWindowText(_T("-"));

	if (m_client->GetRequestFile())
		GetDlgItem(IDC_UPLOADING)->SetWindowText( m_client->GetRequestFile()->GetFileName()  );
	else 
		GetDlgItem(IDC_UPLOADING)->SetWindowText(_T("-"));

	GetDlgItem(IDC_DDUP)->SetWindowText(CastItoXBytes(m_client->GetTransferedDown(), false, false));

	GetDlgItem(IDC_DDOWN)->SetWindowText(CastItoXBytes(m_client->GetTransferedUp(), false, false));

	buffer.Format(_T("%s"), CastItoXBytes(m_client->GetDownloadDatarate(), false, true));
	GetDlgItem(IDC_DAVUR)->SetWindowText(buffer);

	buffer.Format(_T("%s"),CastItoXBytes(m_client->GetDatarate(), false, true));
	GetDlgItem(IDC_DAVDR)->SetWindowText(buffer);
	
	if (m_client->Credits()){
		GetDlgItem(IDC_DUPTOTAL)->SetWindowText(CastItoXBytes(m_client->Credits()->GetDownloadedTotal(), false, false));
		GetDlgItem(IDC_DDOWNTOTAL)->SetWindowText(CastItoXBytes(m_client->Credits()->GetUploadedTotal(), false, false));
		buffer.Format(_T("%.1f"),(float)m_client->Credits()->GetScoreRatio(m_client->GetIP()));
		GetDlgItem(IDC_DRATIO)->SetWindowText(buffer);
		
		if (theApp.clientcredits->CryptoAvailable()){
			switch(m_client->Credits()->GetCurrentIdentState(m_client->GetIP())){
				case IS_NOTAVAILABLE:
					GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTNOSUPPORT));
					break;
				case IS_IDFAILED:
				case IS_IDNEEDED:
				case IS_IDBADGUY:
					GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTFAILED));
					break;
				case IS_IDENTIFIED:
					GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTOK));
					break;
			}
		}
		else
			GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTNOSUPPORT));
	}	
	else{
		GetDlgItem(IDC_DDOWNTOTAL)->SetWindowText(_T("?"));
		GetDlgItem(IDC_DUPTOTAL)->SetWindowText(_T("?"));
		GetDlgItem(IDC_DRATIO)->SetWindowText(_T("?"));
		GetDlgItem(IDC_CDIDENT)->SetWindowText(_T("?"));
	}

	if (m_client->GetUserName()){
		buffer.Format(_T("%.1f"),(float)m_client->GetScore(false,m_client->IsDownloading(),true));
		GetDlgItem(IDC_DRATING)->SetWindowText(buffer);
	}
	else
		GetDlgItem(IDC_DRATING)->SetWindowText(_T("?"));

	if (m_client->GetUploadState() != US_NONE){
		if (!m_client->GetFriendSlot()){
			buffer.Format(_T("%u"),m_client->GetScore(false,m_client->IsDownloading(),false));
			GetDlgItem(IDC_DSCORE)->SetWindowText(buffer);
		}
		else
			GetDlgItem(IDC_DSCORE)->SetWindowText(GetResString(IDS_FRIENDDETAIL));
	}
	else
		GetDlgItem(IDC_DSCORE)->SetWindowText(_T("-"));

	if (m_client->GetKadPort() )
		buffer.Format( _T("%s"), GetResString(IDS_CONNECTED));
	else
		buffer.Format( _T("%s"), GetResString(IDS_DISCONNECTED));
	GetDlgItem(IDC_CLIENTDETAIL_KADCON)->SetWindowText(buffer);
	return true;
}
コード例 #6
0
ファイル: UploadListCtrl.cpp プロジェクト: acat/emule
void CUploadListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	if (!theApp.emuledlg->IsRunning())
		return;
	if (!lpDrawItemStruct->itemData)
		return;
	CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC);
	BOOL bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS));
	if (lpDrawItemStruct->itemState & ODS_SELECTED) {
		if (bCtrlFocused)
			odc->SetBkColor(m_crHighlight);
		else
			odc->SetBkColor(m_crNoHighlight);
	}
	else
		odc->SetBkColor(GetBkColor());
	const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData;
	CMemDC dc(odc, &lpDrawItemStruct->rcItem);
	CFont* pOldFont = dc.SelectObject(GetFont());
	CRect cur_rec(lpDrawItemStruct->rcItem);
	COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText);
    if (client->GetSlotNumber() > theApp.uploadqueue->GetActiveUploadsCount()) {
        dc.SetTextColor(::GetSysColor(COLOR_GRAYTEXT));
    }

	int iOldBkMode;
	if (m_crWindowTextBk == CLR_NONE){
		DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0);
		iOldBkMode = dc.SetBkMode(TRANSPARENT);
	}
	else
		iOldBkMode = OPAQUE;

	CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
	CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
	int iCount = pHeaderCtrl->GetItemCount();
	cur_rec.right = cur_rec.left - 8;
	cur_rec.left += 4;
	CString Sbuffer;
	for (int iCurrent = 0; iCurrent < iCount; iCurrent++)
	{
		int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
		if (!IsColumnHidden(iColumn))
		{
			cur_rec.right += GetColumnWidth(iColumn);
			switch (iColumn)
			{
				case 0:{
					uint8 image;
					if (client->IsFriend())
						image = 4;
					else if (client->GetClientSoft() == SO_EDONKEYHYBRID){
						if (client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 8;
						else
							image = 7;
					}
					else if (client->GetClientSoft() == SO_MLDONKEY){
						if (client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 6;
						else
							image = 5;
					}
					else if (client->GetClientSoft() == SO_SHAREAZA){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 10;
						else
							image = 9;
					}
					else if (client->GetClientSoft() == SO_AMULE){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 12;
						else
							image = 11;
					}
					else if (client->GetClientSoft() == SO_LPHANT){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 14;
						else
							image = 13;
					}
					else if (client->ExtProtocolAvailable()){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 3;
						else
							image = 1;
					}
					else{
						if (client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 2;
						else
							image = 0;
					}

					uint32 nOverlayImage = 0;
					if ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED))
						nOverlayImage |= 1;
					if (client->IsObfuscatedConnectionEstablished())
						nOverlayImage |= 2;
					int iIconPosY = (cur_rec.Height() > 16) ? ((cur_rec.Height() - 16) / 2) : 1;
					POINT point = {cur_rec.left, cur_rec.top + iIconPosY};
					imagelist.Draw(dc,image, point, ILD_NORMAL | INDEXTOOVERLAYMASK(nOverlayImage));

					Sbuffer = client->GetUserName();
					cur_rec.left += 20;
					dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT);
					cur_rec.left -= 20;
					break;
				}
				case 1:
					if (file)
						Sbuffer = file->GetFileName();
					else
						Sbuffer = _T("?");
					break;
				case 2:
					Sbuffer = CastItoXBytes(client->GetDatarate(), false, true);
					break;
				case 3:
					// NOTE: If you change (add/remove) anything which is displayed here, update also the sorting part..
					if (thePrefs.m_bExtControls)
						Sbuffer.Format( _T("%s (%s)"), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false));
					else
						Sbuffer = CastItoXBytes(client->GetSessionUp(), false, false);
					break;
				case 4:
					if (client->HasLowID())
						Sbuffer.Format(_T("%s (%s)"), CastSecondsToHM(client->GetWaitTime()/1000), GetResString(IDS_IDLOW));
					else
						Sbuffer = CastSecondsToHM(client->GetWaitTime()/1000);
					break;
				case 5:
					Sbuffer = CastSecondsToHM(client->GetUpStartTimeDelay()/1000);
					break;
				case 6:
					Sbuffer = client->GetUploadStateDisplayString();
					break;
				case 7:
					cur_rec.bottom--;
					cur_rec.top++;
					client->DrawUpStatusBar(dc, &cur_rec, false, thePrefs.UseFlatBar());
					cur_rec.bottom++;
					cur_rec.top--;
					break;
			}
			if (iColumn != 7 && iColumn != 0)
				dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT);
			cur_rec.left += GetColumnWidth(iColumn);
		}
	}

	//draw rectangle around selected item(s)
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
	{
		RECT outline_rec = lpDrawItemStruct->rcItem;

		outline_rec.top--;
		outline_rec.bottom++;
		dc.FrameRect(&outline_rec, &CBrush(GetBkColor()));
		outline_rec.top++;
		outline_rec.bottom--;
		outline_rec.left++;
		outline_rec.right--;

		if (bCtrlFocused)
			dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine));
		else
			dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine));
	}

	if (m_crWindowTextBk == CLR_NONE)
		dc.SetBkMode(iOldBkMode);
	dc.SelectObject(pOldFont);
	dc.SetTextColor(crOldTextColor);
}
コード例 #7
0
BOOL CClientDetailPage::OnSetActive()
{
	if (!CResizablePage::OnSetActive())
		return FALSE;

	if (m_bDataChanged)
	{

		//Xman Code Fix
		//don't know how this happend, but happend with a friend:
		if(m_paClients==NULL)
			return FALSE;
		//Xman end

		CUpDownClient* client = STATIC_DOWNCAST(CUpDownClient, (*m_paClients)[0]);

		CString buffer;
		if (client->GetUserName())
			GetDlgItem(IDC_DNAME)->SetWindowText(client->GetUserName());
		else
			GetDlgItem(IDC_DNAME)->SetWindowText(_T("?"));
		
		//EastShare Start - added by AndCycle, IP to Country
		GetDlgItem(IDC_DLOC)->SetWindowText(client->GetCountryName(true));
		//EastShare End - added by AndCycle, IP to Country

		if (client->HasValidHash())
			GetDlgItem(IDC_DHASH)->SetWindowText(md4str(client->GetUserHash()));
		else
			GetDlgItem(IDC_DHASH)->SetWindowText(_T("?"));
		
		//Xman ModId
		/*
		GetDlgItem(IDC_DSOFT)->SetWindowText(client->GetClientSoftVer());
		*/
		GetDlgItem(IDC_DSOFT)->SetWindowText(client->DbgGetFullClientSoftVer());
		//Xman end

		if (client->SupportsCryptLayer() && thePrefs.IsClientCryptLayerSupported() && (client->RequestsCryptLayer() || thePrefs.IsClientCryptLayerRequested()) 
			&& (client->IsObfuscatedConnectionEstablished() || !(client->socket != NULL && client->socket->IsConnected())))
		{
			buffer = GetResString(IDS_ENABLED);
		}
		else if (client->SupportsCryptLayer())
			buffer = GetResString(IDS_SUPPORTED);
		else
			buffer = GetResString(IDS_IDENTNOSUPPORT);
#if defined(_DEBUG)
		if (client->IsObfuscatedConnectionEstablished())
			buffer += _T("(In Use)");
#endif
		GetDlgItem(IDC_OBFUSCATION_STAT)->SetWindowText(buffer);

		buffer.Format(_T("%s"),(client->HasLowID() ? GetResString(IDS_IDLOW):GetResString(IDS_IDHIGH)));
		GetDlgItem(IDC_DID)->SetWindowText(buffer);
		
		if (client->GetServerIP()){
			GetDlgItem(IDC_DSIP)->SetWindowText(ipstr(client->GetServerIP()));
			CServer* cserver = theApp.serverlist->GetServerByIPTCP(client->GetServerIP(), client->GetServerPort());
			if (cserver)
				GetDlgItem(IDC_DSNAME)->SetWindowText(cserver->GetListName());
			else
				GetDlgItem(IDC_DSNAME)->SetWindowText(_T("?"));
		}
		else{
			GetDlgItem(IDC_DSIP)->SetWindowText(_T("?"));
			GetDlgItem(IDC_DSNAME)->SetWindowText(_T("?"));
		}

		//Xman Queuerank at clientdetail
		if(client->GetUploadState()==US_ONUPLOADQUEUE)
			buffer.Format(_T("%u"),theApp.uploadqueue->GetWaitingPosition(client));
		else
			buffer.Format(_T("-"));
		GetDlgItem(IDC_DOWNQUEUERANK)->SetWindowText(buffer);
		if(client->GetDownloadState()==DS_ONQUEUE)
		{
			if(client->IsRemoteQueueFull())
				buffer = GetResString(IDS_QUEUEFULL);
			else
				buffer.Format(_T("%u"), client->GetRemoteQueueRank());
		}
		else
			buffer.Format(_T("-"));
		GetDlgItem(IDC_UPLOADQUEURANK)->SetWindowText(buffer);
		//Xman end

		//Xman Anti-Leecher
		if(client->IsLeecher()>0 && client->GetBanMessageString().IsEmpty()==false)
			GetDlgItem(IDC_LEECHERINFO)->SetWindowText(client->GetBanMessageString());
		else
			GetDlgItem(IDC_LEECHERINFO)->SetWindowText(_T(" "));
		//Xman end

		// ==> requpfile optimization [SiRoB] - Stulle
		/*
		CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
		*/
		CKnownFile* file = client->CheckAndGetReqUpFile();
		// <== requpfile optimization [SiRoB] - Stulle
		if (file)
			GetDlgItem(IDC_DDOWNLOADING)->SetWindowText(file->GetFileName());
		else
			GetDlgItem(IDC_DDOWNLOADING)->SetWindowText(_T("-"));

		if (client->GetRequestFile())
			GetDlgItem(IDC_UPLOADING)->SetWindowText( client->GetRequestFile()->GetFileName()  );
		else 
			GetDlgItem(IDC_UPLOADING)->SetWindowText(_T("-"));

		GetDlgItem(IDC_DDUP)->SetWindowText(CastItoXBytes(client->GetTransferredDown(), false, false));

		GetDlgItem(IDC_DDOWN)->SetWindowText(CastItoXBytes(client->GetTransferredUp(), false, false));

		buffer.Format(_T("%s"), CastItoXBytes(client->GetDownloadDatarate(), false, true));
		GetDlgItem(IDC_DAVUR)->SetWindowText(buffer);

		//Xman // Maella -Accurate measure of bandwidth
		/*
		buffer.Format(_T("%s"),CastItoXBytes(client->GetDatarate(), false, true));
		*/
		buffer.Format(_T("%s"),CastItoXBytes(client->GetUploadDatarate(), false, true));
		//Xman end
		GetDlgItem(IDC_DAVDR)->SetWindowText(buffer);
		
		if (client->Credits()){
			GetDlgItem(IDC_DUPTOTAL)->SetWindowText(CastItoXBytes(client->Credits()->GetDownloadedTotal(), false, false));
			GetDlgItem(IDC_DDOWNTOTAL)->SetWindowText(CastItoXBytes(client->Credits()->GetUploadedTotal(), false, false));
			// Xman Creditsystem
			/*
			buffer.Format(_T("%.1f"),(float)client->Credits()->GetScoreRatio(client->GetIP()));
			*/
			// ==> CreditSystems [EastShare/ MorphXT] - Stulle
			if (thePrefs.GetCreditSystem() == 7) // is Xman CS¿
			buffer.Format(_T("%.1f %+.1f [%.1f]"),(float)client->Credits()->GetScoreRatio(client)- (float)client->Credits()->GetBonusFaktor(client),(float)client->Credits()->GetBonusFaktor(client),(float)client->Credits()->GetMyScoreRatio(client->GetIP()));	//  See own credits VQB
			else
				buffer.Format(_T("%.1f [%.1f]"),(float)client->Credits()->GetScoreRatio(client),(float)client->Credits()->GetMyScoreRatio(client->GetIP()));	//  See own credits VQB
			// <== CreditSystems [EastShare/ MorphXT] - Stulle
			//Xman Creditsystem end
			GetDlgItem(IDC_DRATIO)->SetWindowText(buffer);
			
			if (theApp.clientcredits->CryptoAvailable()){
				switch(client->Credits()->GetCurrentIdentState(client->GetIP())){
					case IS_NOTAVAILABLE:
						GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTNOSUPPORT));
						break;
					case IS_IDFAILED:
					case IS_IDNEEDED:
					case IS_IDBADGUY:
						GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTFAILED));
						break;
					case IS_IDENTIFIED:
						GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTOK));
						break;
				}
			}
			else
				GetDlgItem(IDC_CDIDENT)->SetWindowText(GetResString(IDS_IDENTNOSUPPORT));
		}	
		else{
			GetDlgItem(IDC_DDOWNTOTAL)->SetWindowText(_T("?"));
			GetDlgItem(IDC_DUPTOTAL)->SetWindowText(_T("?"));
			GetDlgItem(IDC_DRATIO)->SetWindowText(_T("?"));
			GetDlgItem(IDC_CDIDENT)->SetWindowText(_T("?"));
		}

		if (client->GetUserName() && client->Credits()!=NULL){
			buffer.Format(_T("%.1f"),(float)client->GetScore(false,client->IsDownloading(),true));
			GetDlgItem(IDC_DRATING)->SetWindowText(buffer);
		}
		else
			GetDlgItem(IDC_DRATING)->SetWindowText(_T("?"));

		if (client->GetUploadState() != US_NONE && client->Credits()!=NULL){
			if (!client->GetFriendSlot()){
				buffer.Format(_T("%u"),client->GetScore(false,client->IsDownloading(),false));
				GetDlgItem(IDC_DSCORE)->SetWindowText(buffer);
			}
			else
				GetDlgItem(IDC_DSCORE)->SetWindowText(GetResString(IDS_FRIENDDETAIL));
		}
		else
			GetDlgItem(IDC_DSCORE)->SetWindowText(_T("-"));

		if (client->GetKadPort() )
			buffer.Format( _T("%s"), GetResString(IDS_CONNECTED));
		else
			buffer.Format( _T("%s"), GetResString(IDS_DISCONNECTED));
		GetDlgItem(IDC_CLIENTDETAIL_KADCON)->SetWindowText(buffer);

		m_bDataChanged = false;
	}
	return TRUE;
}
コード例 #8
0
ファイル: AICHSyncThread.cpp プロジェクト: e1z0/sMule
int CAICHSyncThread::Run()
{
	//MORPH START SLUGFILLER: SafeHash
	CReadWriteLock lock(&theApp.m_threadlock);
	if (!lock.ReadLock(0))
		return 0;
	// MORPH END SLUGFILLER: SafeHash
	if ( !theApp.emuledlg->IsRunning() )
		return 0;
	// we need to keep a lock on this file while the thread is running
	CSingleLock lockKnown2Met(&CAICHRecoveryHashSet::m_mutKnown2File);
	lockKnown2Met.Lock();
	
	CSafeFile file;
	bool bJustCreated = ConvertToKnown2ToKnown264(&file);
	
	// we collect all masterhashs which we find in the known2.met and store them in a list
	CList<CAICHHash> liKnown2Hashs;
	CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR);
	fullpath.Append(KNOWN2_MET_FILENAME);
	
	CFileException fexp;
	uint32 nLastVerifiedPos = 0;

	if (!bJustCreated && !file.Open(fullpath,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyNone, &fexp)){
		if (fexp.m_cause != CFileException::fileNotFound){
			CString strError(_T("Failed to load ") KNOWN2_MET_FILENAME _T(" file"));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(LOG_STATUSBAR, _T("%s"), strError);
		}
		return false;
	}
	try {
		if (file.GetLength() >= 1){
			uint8 header = file.ReadUInt8();
			if (header != KNOWN2_MET_VERSION){
				AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName());
			}
			//setvbuf(file.m_pStream, NULL, _IOFBF, 16384);
			uint32 nExistingSize = (UINT)file.GetLength();
			uint32 nHashCount;
			while (file.GetPosition() < nExistingSize){
				liKnown2Hashs.AddTail(CAICHHash(&file));
				nHashCount = file.ReadUInt32();
				if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){
					AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName());
				}
				// skip the rest of this hashset
				file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
				nLastVerifiedPos = (UINT)file.GetPosition();
			}
		}
		else
			file.WriteUInt8(KNOWN2_MET_VERSION);
	}
	catch(CFileException* error){
		if (error->m_cause == CFileException::endOfFile){
			LogError(LOG_STATUSBAR,GetResString(IDS_ERR_MET_BAD), KNOWN2_MET_FILENAME);
			// truncate the file to the size to the last verified valid pos
			try{
				file.SetLength(nLastVerifiedPos);
				if (file.GetLength() == 0){
					file.SeekToBegin();
					file.WriteUInt8(KNOWN2_MET_VERSION);
				}
			}
			catch(CFileException* error2){
				error2->Delete();
			}
		}
		else{
			TCHAR buffer[MAX_CFEXP_ERRORMSG];
			error->GetErrorMessage(buffer, ARRSIZE(buffer));
			LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer);
		}
		error->Delete();
		return false;
	}
	
	// now we check that all files which are in the sharedfilelist have a corresponding hash in out list
	// those who don'T are added to the hashinglist
	CList<CAICHHash> liUsedHashs;	
	CSingleLock sharelock(&theApp.sharedfiles->m_mutWriteList);
	sharelock.Lock();

	bool bDbgMsgCreatingPartHashs = true;
	for (int i = 0; i < theApp.sharedfiles->GetCount(); i++){
		CKnownFile* pCurFile = theApp.sharedfiles->GetFileByIndex(i);
		if (pCurFile != NULL && !pCurFile->IsPartFile() )
		{
			if (theApp.emuledlg==NULL || !theApp.emuledlg->IsRunning()) // in case of shutdown while still hashing
				return 0;
			if (pCurFile->GetFileIdentifier().HasAICHHash()){
				bool bFound = false;
				for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;)
				{
					CAICHHash current_hash = liKnown2Hashs.GetNext(pos);
					if (current_hash == pCurFile->GetFileIdentifier().GetAICHHash()){
						bFound = true;
						liUsedHashs.AddTail(current_hash);
						pCurFile->SetAICHRecoverHashSetAvailable(true);
						// Has the file the proper AICH Parthashset? If not probably upgrading, create it
						if (!pCurFile->GetFileIdentifier().HasExpectedAICHHashCount())
						{
							if (bDbgMsgCreatingPartHashs)
							{
								bDbgMsgCreatingPartHashs = false;
								DebugLogWarning(_T("Missing AICH Part Hashsets for known files - maybe upgrading from earlier version. Creating them out of full AICH Recovery Hashsets, shouldn't take too long"));
							}
							CAICHRecoveryHashSet tempHashSet(pCurFile, pCurFile->GetFileSize());
							tempHashSet.SetMasterHash(pCurFile->GetFileIdentifier().GetAICHHash(), AICH_HASHSETCOMPLETE);
							if (!tempHashSet.LoadHashSet())
							{
								ASSERT( false );
								DebugLogError(_T("Failed to load full AICH Recovery Hashset - known2.met might be corrupt. Unable to create AICH Part Hashset - %s"), pCurFile->GetFileName());
							}
							else
							{
								if (!pCurFile->GetFileIdentifier().SetAICHHashSet(tempHashSet))
								{
									DebugLogError(_T("Failed to create AICH Part Hashset out of full AICH Recovery Hashset - %s"), pCurFile->GetFileName());
									ASSERT( false );
								}
								ASSERT(pCurFile->GetFileIdentifier().HasExpectedAICHHashCount());
							}
						}
						//theApp.QueueDebugLogLine(false, _T("%s - %s"), current_hash.GetString(), pCurFile->GetFileName());
						/*#ifdef _DEBUG
						// in debugmode we load and verify all hashsets
						CAICHRecoveryHashSet* pTempHashSet = new CAICHRecoveryHashSet(pCurFile);
						pTempHashSet->SetFileSize(pCurFile->GetFileSize());
						pTempHashSet->SetMasterHash(pCurFile->GetFileIdentifier().GetAICHHash(), AICH_HASHSETCOMPLETE)
						ASSERT( pTempHashSet->LoadHashSet() );
						delete pTempHashSet;
#endif*/
						break;
					}
				}
				if (bFound) // hashset is available, everything fine with this file
					continue;
			}
			pCurFile->SetAICHRecoverHashSetAvailable(false);
			m_liToHash.AddTail(pCurFile);
		}
	}
	sharelock.Unlock();

	// removed all unused AICH hashsets from known2.met
	if (liUsedHashs.GetCount() != liKnown2Hashs.GetCount() && 
		// EastShare START - Added by TAHO, .met file control
		/*
		(!thePrefs.IsRememberingDownloadedFiles() || thePrefs.DoPartiallyPurgeOldKnownFiles()))
		*/
			(!thePrefs.IsRememberingDownloadedFiles() ||
			  thePrefs.DoPartiallyPurgeOldKnownFiles() || 
			  thePrefs.DoCompletlyPurgeOldKnownFiles() ||
			  thePrefs.DoRemoveAichImmediatly()
			)
		)
		// EastShare END   - Added by TAHO, .met file control
	{
		file.SeekToBegin();
		try {
			uint8 header = file.ReadUInt8();
			if (header != KNOWN2_MET_VERSION){
				AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName());
			}

			uint32 nExistingSize = (UINT)file.GetLength();
			uint32 nHashCount;
			ULONGLONG posWritePos = file.GetPosition();
			ULONGLONG posReadPos = file.GetPosition();
			uint32 nPurgeCount = 0;
			uint32 nPurgeBecauseOld = 0;
			while (file.GetPosition() < nExistingSize){
				CAICHHash aichHash(&file);
				nHashCount = file.ReadUInt32();
				if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){
					AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName());
				}
				if (!thePrefs.IsRememberingDownloadedFiles() && liUsedHashs.Find(aichHash) == NULL)
				{
					// unused hashset skip the rest of this hashset
					file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
					nPurgeCount++;
				}
				else if (thePrefs.IsRememberingDownloadedFiles() && theApp.knownfiles->ShouldPurgeAICHHashset(aichHash))
				{
					// EastShare START - Added by TAHO, .met file control
					/*
					ASSERT( thePrefs.DoPartiallyPurgeOldKnownFiles() );
					*/
					ASSERT( thePrefs.DoPartiallyPurgeOldKnownFiles() || thePrefs.DoRemoveAichImmediatly());
					// EastShare END   - Added by TAHO, .met file control
					// also unused (purged) hashset skip the rest of this hashset
					file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
					nPurgeCount++;
					nPurgeBecauseOld++;
				}
				else if(nPurgeCount == 0){
					// used Hashset, but it does not need to be moved as nothing changed yet
					file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current);
					posWritePos = file.GetPosition();
					CAICHRecoveryHashSet::AddStoredAICHHash(aichHash);
				}
				else{
					// used Hashset, move position in file
					BYTE* buffer = new BYTE[nHashCount*CAICHHash::GetHashSize()];
					file.Read(buffer, nHashCount*CAICHHash::GetHashSize());
					posReadPos = file.GetPosition();
					file.Seek(posWritePos, CFile::begin);
					file.Write(aichHash.GetRawHash(), CAICHHash::GetHashSize());
					file.WriteUInt32(nHashCount);
					file.Write(buffer, nHashCount*CAICHHash::GetHashSize());
					delete[] buffer;
					posWritePos = file.GetPosition();
					file.Seek(posReadPos, CFile::begin);
					CAICHRecoveryHashSet::AddStoredAICHHash(aichHash);
				}
			}
			posReadPos = file.GetPosition();
			file.SetLength(posWritePos);
			theApp.QueueDebugLogLine(false, _T("Cleaned up known2.met, removed %u hashsets and purged %u hashsets of old known files (%s)")
				, nPurgeCount - nPurgeBecauseOld, nPurgeBecauseOld, CastItoXBytes(posReadPos-posWritePos)); 

			file.Flush();
			file.Close();
		}
		catch(CFileException* error){
			if (error->m_cause == CFileException::endOfFile){
				// we just parsed this files some ms ago, should never happen here
				ASSERT( false );
			}
			else{
				TCHAR buffer[MAX_CFEXP_ERRORMSG];
				error->GetErrorMessage(buffer, ARRSIZE(buffer));
				LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer);
			}
			error->Delete();
			return false;
		}
	}
	else
	{
		// remember (/index) all hashs which are stored in the file for faster checking lateron
		for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;)
		{
			CAICHRecoveryHashSet::AddStoredAICHHash(liKnown2Hashs.GetNext(pos));
		}
	}
	lockKnown2Met.Unlock();
	// warn the user if he just upgraded
	if (thePrefs.IsFirstStart() && !m_liToHash.IsEmpty() && !bJustCreated){
		LogWarning(GetResString(IDS_AICH_WARNUSER));
	}	
	if (!m_liToHash.IsEmpty()){
		theApp.QueueLogLine(true, GetResString(IDS_AICH_SYNCTOTAL), m_liToHash.GetCount() );
		theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(m_liToHash.GetCount());
		// let first all normal hashing be done before starting out synchashing
		CSingleLock sLock1(&theApp.hashing_mut); // only one filehash at a time
		while (theApp.sharedfiles->GetHashingCount() != 0){
			Sleep(100);
			if (!CemuleDlg::IsRunning())
				return 0;
		}
		sLock1.Lock();
		uint32 cDone = 0;
		for (POSITION pos = m_liToHash.GetHeadPosition();pos != 0; cDone++)
		{
			if (!CemuleDlg::IsRunning()){ // in case of shutdown while still hashing
				return 0;
			}
			theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(m_liToHash.GetCount()-cDone);
			if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL)
				theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount();
			CKnownFile* pCurFile = m_liToHash.GetNext(pos);
			// just to be sure that the file hasnt been deleted lately
			if (!(theApp.knownfiles->IsKnownFile(pCurFile) && theApp.sharedfiles->GetFileByID(pCurFile->GetFileHash())) )
				continue;
			theApp.QueueLogLine(false, GetResString(IDS_AICH_CALCFILE), pCurFile->GetFileName());
			if(!pCurFile->CreateAICHHashSetOnly())
				theApp.QueueDebugLogLine(false, _T("Failed to create AICH Hashset while sync. for file %s"), pCurFile->GetFileName());
		}

		theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(0);
		if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL)
			theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount();
		sLock1.Unlock();
	}

	theApp.QueueDebugLogLine(false, _T("AICHSyncThread finished"));
	return 0;
}
コード例 #9
0
ファイル: QueueListCtrl.cpp プロジェクト: machado2/emule
void CQueueListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	if (!theApp.emuledlg->IsRunning())
		return;
	if (!lpDrawItemStruct->itemData)
		return;
	CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC);
	BOOL bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS));
	if (lpDrawItemStruct->itemState & ODS_SELECTED) {
		if (bCtrlFocused)
			odc->SetBkColor(m_crHighlight);
		else
			odc->SetBkColor(m_crNoHighlight);
	}
	else
		odc->SetBkColor(GetBkColor());
	const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData;
	CMemDC dc(odc, &lpDrawItemStruct->rcItem);
	CFont* pOldFont = dc.SelectObject(GetFont());
	CRect cur_rec(lpDrawItemStruct->rcItem);
	COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText);

	int iOldBkMode;
	if (m_crWindowTextBk == CLR_NONE){
		DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0);
		iOldBkMode = dc.SetBkMode(TRANSPARENT);
	}
	else
		iOldBkMode = OPAQUE;

	CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
	CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
	int iCount = pHeaderCtrl->GetItemCount();
	cur_rec.right = cur_rec.left - 8;
	cur_rec.left += 4;
	CString Sbuffer;
	for(int iCurrent = 0; iCurrent < iCount; iCurrent++){
		int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
		if( !IsColumnHidden(iColumn) ){
			cur_rec.right += GetColumnWidth(iColumn);
			switch(iColumn){
				case 0:{
					uint8 image;
					if (client->IsFriend())
						image = 4;
					else if (client->GetClientSoft() == SO_EDONKEYHYBRID){
						if (client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 8;
						else
							image = 7;
					}
					else if (client->GetClientSoft() == SO_MLDONKEY){
						if (client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 6;
						else
							image = 5;
					}
					else if (client->GetClientSoft() == SO_SHAREAZA){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 10;
						else
							image = 9;
					}
					else if (client->GetClientSoft() == SO_AMULE){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 12;
						else
							image = 11;
					}
					else if (client->GetClientSoft() == SO_LPHANT){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 14;
						else
							image = 13;
					}
					else if (client->ExtProtocolAvailable()){
						if(client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 3;
						else
							image = 1;
					}
					else{
						if (client->credits->GetScoreRatio(client->GetIP()) > 1)
							image = 2;
						else
							image = 0;
					}

					POINT point = {cur_rec.left, cur_rec.top+1};
					imagelist.Draw(dc,image, point, ILD_NORMAL | ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED) ? INDEXTOOVERLAYMASK(1) : 0));
					Sbuffer = client->GetUserName();
					cur_rec.left +=20;
					dc.DrawText(Sbuffer,Sbuffer.GetLength(),&cur_rec,DLC_DT_TEXT);
					cur_rec.left -=20;
					break;
				}
				case 1:
					if(file)
						Sbuffer = file->GetFileName();
					else
						Sbuffer = _T("?");
					break;
				case 2:
					if(file){
						switch (file->GetUpPriority()) {
							case PR_VERYLOW : {
								Sbuffer = GetResString(IDS_PRIOVERYLOW);
								break; }
							case PR_LOW : {
								if( file->IsAutoUpPriority() )
									Sbuffer = GetResString(IDS_PRIOAUTOLOW);
								else
									Sbuffer = GetResString(IDS_PRIOLOW);
								break; }
							case PR_NORMAL : {
								if( file->IsAutoUpPriority() )
									Sbuffer = GetResString(IDS_PRIOAUTONORMAL);
								else
									Sbuffer = GetResString(IDS_PRIONORMAL);
								break; }
							case PR_HIGH : {
								if( file->IsAutoUpPriority() )
									Sbuffer = GetResString(IDS_PRIOAUTOHIGH);
								else
									Sbuffer = GetResString(IDS_PRIOHIGH);
								break; }
							case PR_VERYHIGH : {
								Sbuffer = GetResString(IDS_PRIORELEASE);
								break; }
							default:
								Sbuffer.Empty();
						}
					}
					else
						Sbuffer = _T("?");
					break;
				case 3:
					Sbuffer.Format(_T("%i"),client->GetScore(false,false,true));
					break;
				case 4:
					if (client->HasLowID()){
						if (client->m_bAddNextConnect)
							Sbuffer.Format(_T("%i ****"),client->GetScore(false));
						else
                            Sbuffer.Format(_T("%i LowID"),client->GetScore(false));
					}
					else
						Sbuffer.Format(_T("%i"),client->GetScore(false));
					break;
				case 5:
					Sbuffer.Format(_T("%i"),client->GetAskedCount());
					break;
				case 6:
					Sbuffer = CastSecondsToHM((::GetTickCount() - client->GetLastUpRequest())/1000);
					break;
				case 7:
					Sbuffer = CastSecondsToHM((::GetTickCount() - client->GetWaitStartTime())/1000);
					break;
				case 8:
					if(client->IsBanned())
						Sbuffer = GetResString(IDS_YES);
					else
						Sbuffer = GetResString(IDS_NO);
					break;
				case 9:
					if( client->GetUpPartCount()){
						cur_rec.bottom--;
						cur_rec.top++;
						client->DrawUpStatusBar(dc,&cur_rec,false,thePrefs.UseFlatBar());
						cur_rec.bottom++;
						cur_rec.top--;
					}
					break;
		   	}
			if( iColumn != 9 && iColumn != 0)
				dc.DrawText(Sbuffer,Sbuffer.GetLength(),&cur_rec,DLC_DT_TEXT);
			cur_rec.left += GetColumnWidth(iColumn);
		}
	}

	// draw rectangle around selected item(s)
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
	{
		RECT outline_rec = lpDrawItemStruct->rcItem;

		outline_rec.top--;
		outline_rec.bottom++;
		dc.FrameRect(&outline_rec, &CBrush(GetBkColor()));
		outline_rec.top++;
		outline_rec.bottom--;
		outline_rec.left++;
		outline_rec.right--;

		if(bCtrlFocused)
			dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine));
		else
			dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine));
	}
	
	if (m_crWindowTextBk == CLR_NONE)
		dc.SetBkMode(iOldBkMode);
	dc.SelectObject(pOldFont);
	dc.SetTextColor(crOldTextColor);
}
コード例 #10
0
ファイル: UploadQueue.cpp プロジェクト: machado2/emule
/**
 * Add a client to the waiting queue for uploads.
 *
 * @param client address of the client that should be added to the waiting queue
 *
 * @param bIgnoreTimelimit don't check time limit to possibly ban the client.
 */
void CUploadQueue::AddClientToQueue(CUpDownClient* client, bool bIgnoreTimelimit)
{
	//This is to keep users from abusing the limits we put on lowID callbacks.
	//1)Check if we are connected to any network and that we are a lowID.
	//(Although this check shouldn't matter as they wouldn't have found us..
	// But, maybe I'm missing something, so it's best to check as a precaution.)
	//2)Check if the user is connected to Kad. We do allow all Kad Callbacks.
	//3)Check if the user is in our download list or a friend..
	//We give these users a special pass as they are helping us..
	//4)Are we connected to a server? If we are, is the user on the same server?
	//TCP lowID callbacks are also allowed..
	//5)If the queue is very short, allow anyone in as we want to make sure
	//our upload is always used.
	if (theApp.IsConnected() 
		&& theApp.IsFirewalled()
		&& !client->GetKadPort()
		&& client->GetDownloadState() == DS_NONE 
		&& !client->IsFriend()
		&& theApp.serverconnect
		&& !theApp.serverconnect->IsLocalServer(client->GetServerIP(),client->GetServerPort())
		&& GetWaitingUserCount() > 50)
		return;
	client->AddAskedCount();
	client->SetLastUpRequest();
	if (!bIgnoreTimelimit)
		client->AddRequestCount(client->GetUploadFileID());
	if (client->IsBanned())
		return;
	uint16 cSameIP = 0;
	// check for double
	POSITION pos1, pos2;
	for (pos1 = waitinglist.GetHeadPosition();( pos2 = pos1 ) != NULL;)
	{
		waitinglist.GetNext(pos1);
		CUpDownClient* cur_client= waitinglist.GetAt(pos2);
		if (cur_client == client)
		{	
			if (client->m_bAddNextConnect && AcceptNewClient(client->m_bAddNextConnect))
			{
				//Special care is given to lowID clients that missed their upload slot
				//due to the saving bandwidth on callbacks.
				if(thePrefs.GetLogUlDlEvents())
					AddDebugLogLine(true, _T("Adding ****lowid when reconnecting. Client: %s"), client->DbgGetClientInfo());
				client->m_bAddNextConnect = false;
				RemoveFromWaitingQueue(client, true);
				AddUpNextClient(_T("Adding ****lowid when reconnecting."), client);
				return;
			}
			client->SendRankingInfo();
			theApp.emuledlg->transferwnd->queuelistctrl.RefreshClient(client);
			return;			
		}
		else if ( client->Compare(cur_client) ) 
		{
			theApp.clientlist->AddTrackClient(client); // in any case keep track of this client

			// another client with same ip:port or hash
			// this happens only in rare cases, because same userhash / ip:ports are assigned to the right client on connecting in most cases
			if (cur_client->credits != NULL && cur_client->credits->GetCurrentIdentState(cur_client->GetIP()) == IS_IDENTIFIED)
			{
				//cur_client has a valid secure hash, don't remove him
				if (thePrefs.GetVerbose())
					AddDebugLogLine(false,CString(GetResString(IDS_SAMEUSERHASH)),client->GetUserName(),cur_client->GetUserName(),client->GetUserName() );
				return;
			}
			if (client->credits != NULL && client->credits->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED)
			{
				//client has a valid secure hash, add him remove other one
				if (thePrefs.GetVerbose())
					AddDebugLogLine(false,CString(GetResString(IDS_SAMEUSERHASH)),client->GetUserName(),cur_client->GetUserName(),cur_client->GetUserName() );
				RemoveFromWaitingQueue(pos2,true);
				if (!cur_client->socket)
				{
					if(cur_client->Disconnected(_T("AddClientToQueue - same userhash 1")))
						delete cur_client;
				}
			}
			else
			{
				// remove both since we do not know who the bad one is
				if (thePrefs.GetVerbose())
					AddDebugLogLine(false,CString(GetResString(IDS_SAMEUSERHASH)),client->GetUserName(),cur_client->GetUserName(),"Both" );
				RemoveFromWaitingQueue(pos2,true);	
				if (!cur_client->socket)
				{
					if(cur_client->Disconnected(_T("AddClientToQueue - same userhash 2")))
						delete cur_client;
				}
				return;
			}
		}
		else if (client->GetIP() == cur_client->GetIP())
		{
			// same IP, different port, different userhash
			cSameIP++;
		}
	}
	if (cSameIP >= 3)
	{
		// do not accept more than 3 clients from the same IP
		if (thePrefs.GetVerbose())
			DEBUG_ONLY( AddDebugLogLine(false,_T("%s's (%s) request to enter the queue was rejected, because of too many clients with the same IP"), client->GetUserName(), ipstr(client->GetConnectIP())) );
		return;
	}
	else if (theApp.clientlist->GetClientsFromIP(client->GetIP()) >= 3)
	{
		if (thePrefs.GetVerbose())
			DEBUG_ONLY( AddDebugLogLine(false,_T("%s's (%s) request to enter the queue was rejected, because of too many clients with the same IP (found in TrackedClientsList)"), client->GetUserName(), ipstr(client->GetConnectIP())) );
		return;
	}
	// done

	// statistic values
	CKnownFile* reqfile = theApp.sharedfiles->GetFileByID((uchar*)client->GetUploadFileID());
	if (reqfile)
		reqfile->statistic.AddRequest();

	// emule collection will bypass the queue
	if (reqfile != NULL && CCollection::HasCollectionExtention(reqfile->GetFileName()) && reqfile->GetFileSize() < MAXPRIORITYCOLL_SIZE
		&& !client->IsDownloading() && client->socket != NULL && client->socket->IsConnected())
	{
		client->SetCollectionUploadSlot(true);
		RemoveFromWaitingQueue(client, true);
		AddUpNextClient(_T("Collection Priority Slot"), client);
		return;
	}
	else
		client->SetCollectionUploadSlot(false);

   // cap the list
    // the queue limit in prefs is only a soft limit. Hard limit is 25% higher, to let in powershare clients and other
    // high ranking clients after soft limit has been reached
    uint32 softQueueLimit = thePrefs.GetQueueSize();
    uint32 hardQueueLimit = thePrefs.GetQueueSize() + max(thePrefs.GetQueueSize()/4, 200);

    // if soft queue limit has been reached, only let in high ranking clients
    if ((uint32)waitinglist.GetCount() >= hardQueueLimit ||
        (uint32)waitinglist.GetCount() >= softQueueLimit && // soft queue limit is reached
        (client->IsFriend() && client->GetFriendSlot()) == false && // client is not a friend with friend slot
        client->GetCombinedFilePrioAndCredit() < GetAverageCombinedFilePrioAndCredit()) { // and client has lower credits/wants lower prio file than average client in queue

        // then block client from getting on queue
		return;
	}
	if (client->IsDownloading())
	{
		// he's already downloading and wants probably only another file
		if (thePrefs.GetDebugClientTCPLevel() > 0)
			DebugSend("OP__AcceptUploadReq", client);
		Packet* packet = new Packet(OP_ACCEPTUPLOADREQ,0);
		theStats.AddUpDataOverheadFileRequest(packet->size);
		client->socket->SendPacket(packet,true);
		return;
	}
	if (waitinglist.IsEmpty() && AcceptNewClient())
	{
		AddUpNextClient(_T("Direct add with empty queue."), client);
	}
	else
	{
		waitinglist.AddTail(client);
		client->SetUploadState(US_ONUPLOADQUEUE);
		theApp.emuledlg->transferwnd->queuelistctrl.AddClient(client,true);
		theApp.emuledlg->transferwnd->ShowQueueCount(waitinglist.GetCount());
		client->SendRankingInfo();
	}
}
コード例 #11
0
ファイル: KnownFileList.cpp プロジェクト: acat/emule
bool CKnownFileList::SafeAddKFile(CKnownFile* toadd)
{
	bool bRemovedDuplicateSharedFile = false;
	CCKey key(toadd->GetFileHash());
	CKnownFile* pFileInMap;
	if (m_Files_map.Lookup(key, pFileInMap))
	{
		TRACE(_T("%hs: Already in known list:   %s \"%s\"\n"), __FUNCTION__, md4str(pFileInMap->GetFileHash()), pFileInMap->GetFileName());
		TRACE(_T("%hs: Old entry replaced with: %s \"%s\"\n"), __FUNCTION__, md4str(toadd->GetFileHash()), toadd->GetFileName());

		// if we hash files which are already in known file list and add them later (when the hashing thread is finished),
		// we can not delete any already available entry from known files list. that entry can already be used by the
		// shared file list -> crash.

		m_Files_map.RemoveKey(CCKey(pFileInMap->GetFileHash()));
		//This can happen in a couple situations..
		//File was renamed outside of eMule.. 
		//A user decided to redownload a file he has downloaded and unshared..
		//RemovingKeyWords I believe is not thread safe if I'm looking at this right.
		//Not sure of a good solution yet..
		if (theApp.sharedfiles)
		{
#if 0
			// This may crash the client because of dangling ptr in shared files ctrl.
			// This may happen if a file is re-shared which is also currently downloaded.
			// After the file was downloaded (again) there is a dangl. ptr in shared files 
			// ctrl.
			// Actually that's also wrong in some cases: Keywords are not always removed
			// because the wrong ptr is used to search for in keyword publish list.
			theApp.sharedfiles->RemoveKeywords(pFileInMap);
#else
			// This solves the problem with dangl. ptr in shared files ctrl,
			// but creates a new bug. It may lead to unshared files! Even 
			// worse it may lead to files which are 'shared' in GUI but 
			// which are though not shared 'logically'.
			//
			// To reduce the harm, remove the file from shared files list, 
			// only if really needed. Right now this 'harm' applies for files
			// which are re-shared and then completed (again) because they were
			// also in download queue (they were added there when the already
			// available file was not in shared file list).
			if (theApp.sharedfiles->IsFilePtrInList(pFileInMap))
				bRemovedDuplicateSharedFile = theApp.sharedfiles->RemoveFile(pFileInMap);
#endif
			ASSERT( !theApp.sharedfiles->IsFilePtrInList(pFileInMap) );
		}
		//Double check to make sure this is the same file as it's possible that a two files have the same hash.
		//Maybe in the furture we can change the client to not just use Hash as a key throughout the entire client..
		ASSERT( toadd->GetFileSize() == pFileInMap->GetFileSize() );
		ASSERT( toadd != pFileInMap );
		if (toadd->GetFileSize() == pFileInMap->GetFileSize())
			toadd->statistic.MergeFileStats(&pFileInMap->statistic);

		ASSERT( theApp.sharedfiles==NULL || !theApp.sharedfiles->IsFilePtrInList(pFileInMap) );
		ASSERT( theApp.downloadqueue==NULL || !theApp.downloadqueue->IsPartFile(pFileInMap) );

		// Quick fix: If we downloaded already downloaded files again and if those files all had the same file names
		// and were renamed during file completion, we have a pending ptr in transfer window.
		if (theApp.emuledlg && theApp.emuledlg->transferwnd && theApp.emuledlg->transferwnd->downloadlistctrl.m_hWnd)
			theApp.emuledlg->transferwnd->downloadlistctrl.RemoveFile((CPartFile*)pFileInMap);

		delete pFileInMap;
	}
	m_Files_map.SetAt(key, toadd);
	if (bRemovedDuplicateSharedFile) {
		theApp.sharedfiles->SafeAddKFile(toadd);
	}
	return true;
}
コード例 #12
0
void CUploadListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
    if (!theApp.emuledlg->IsRunning())
        return;
    if (!lpDrawItemStruct->itemData)
        return;

    CMemDC dc(CDC::FromHandle(lpDrawItemStruct->hDC), &lpDrawItemStruct->rcItem);
    BOOL bCtrlFocused;
    InitItemMemDC(dc, lpDrawItemStruct, bCtrlFocused);
    CRect cur_rec(lpDrawItemStruct->rcItem);
    CRect rcClient;
    GetClientRect(&rcClient);

    const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData;

    COLORREF crOldBackColor = dc->GetBkColor(); //Xman PowerRelease

    CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(client->GetUploadFileID());
    CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
    int iCount = pHeaderCtrl->GetItemCount();
    cur_rec.right = cur_rec.left - 8;
    cur_rec.left += 4;
    CString Sbuffer;
    for (int iCurrent = 0; iCurrent < iCount; iCurrent++)
    {
        int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
        if (!IsColumnHidden(iColumn))
        {
            cur_rec.right += GetColumnWidth(iColumn);
            switch (iColumn)
            {
            case 0: {
                uint8 image;
                if (client->IsFriend())
                    image = 4;
                else if (client->GetClientSoft() == SO_EDONKEYHYBRID) {
                    if (client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 8;
                    else
                        image = 7;
                }
                else if (client->GetClientSoft() == SO_MLDONKEY) {
                    if (client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 6;
                    else
                        image = 5;
                }
                else if (client->GetClientSoft() == SO_SHAREAZA) {
                    if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 10;
                    else
                        image = 9;
                }
                else if (client->GetClientSoft() == SO_AMULE) {
                    if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 12;
                    else
                        image = 11;
                }
                else if (client->GetClientSoft() == SO_LPHANT) {
                    if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 14;
                    else
                        image = 13;
                }
                else if (client->ExtProtocolAvailable()) {
                    if(client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 3;
                    else
                        image = 1;
                }
                else {
                    if (client->credits && client->credits->GetScoreRatio(client->GetIP()) > 1)
                        image = 2;
                    else
                        image = 0;
                }

                uint32 nOverlayImage = 0;
                if ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED))
                    nOverlayImage |= 1;
                if (client->IsObfuscatedConnectionEstablished())
                    nOverlayImage |= 2;
                POINT point = {cur_rec.left, cur_rec.top+1};
                imagelist.Draw(dc,image, point, ILD_NORMAL | ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED) ? INDEXTOOVERLAYMASK(1) : 0));
                Sbuffer = client->GetUserName();

                //EastShare Start - added by AndCycle, IP to Country
                CString tempStr;
                tempStr.Format(_T("%s%s"), client->GetCountryName(), Sbuffer);
                Sbuffer = tempStr;

                if(CGlobalVariable::ip2country->ShowCountryFlag()) {
                    cur_rec.left += 20;
                    POINT point2= {cur_rec.left,cur_rec.top+1};
                    CGlobalVariable::ip2country->GetFlagImageList()->DrawIndirect(dc, client->GetCountryFlagIndex(), point2, CSize(18,16), CPoint(0,0), ILD_NORMAL);
                }
                //EastShare End - added by AndCycle, IP to Country

                cur_rec.left += 20;
                dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT);
                cur_rec.left -= 20;

                //EastShare Start - added by AndCycle, IP to Country
                if(CGlobalVariable::ip2country->ShowCountryFlag()) {
                    cur_rec.left-=20;
                }
                //EastShare End - added by AndCycle, IP to Country

                break;
            }
            case 1:
                if (file)
                    Sbuffer = file->GetFileName();
                else
                    Sbuffer = _T("?");
                if(file && file->GetUpPriority()==PR_POWER) ///PowerRelease
                    dc->SetBkColor(RGB(255,225,225));
                break;
            case 2:
                Sbuffer = CastItoXBytes(client->GetDatarate(), false, true);
                break;
            case 3:
                // NOTE: If you change (add/remove) anything which is displayed here, update also the sorting part..
                if (thePrefs.m_bExtControls)
                    Sbuffer.Format( _T("%s (%s)"), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false));
                else
                    Sbuffer = CastItoXBytes(client->GetSessionUp(), false, false);
                break;
            case 4:
                if (client->HasLowID())
                    Sbuffer.Format(_T("%s (%s)"), CastSecondsToHM(client->GetWaitTime()/1000), GetResString(IDS_IDLOW));
                else
                    Sbuffer = CastSecondsToHM(client->GetWaitTime()/1000);
                break;
            case 5:
                Sbuffer = CastSecondsToHM(client->GetUpStartTimeDelay()/1000);
                break;
            case 6:
                Sbuffer = client->GetUploadStateDisplayString();
                break;
            case 7:
                cur_rec.bottom--;
                cur_rec.top++;
                client->DrawUpStatusBar(dc, &cur_rec, false, thePrefs.UseFlatBar());
                cur_rec.bottom++;
                cur_rec.top--;
                break;
            }
            if (iColumn != 7 && iColumn != 0)
                dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT);
            dc->SetBkColor( crOldBackColor );
            cur_rec.left += GetColumnWidth(iColumn);
        }
    }

    //draw rectangle around selected item(s)
    if (lpDrawItemStruct->itemState & ODS_SELECTED)
    {
        RECT outline_rec = lpDrawItemStruct->rcItem;

        outline_rec.top--;
        outline_rec.bottom++;
        dc.FrameRect(&outline_rec, &CBrush(GetBkColor()));
        outline_rec.top++;
        outline_rec.bottom--;
        outline_rec.left++;
        outline_rec.right--;

        if (bCtrlFocused)
            dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine));
        else
            dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine));
    }

    /*
    	if (m_crWindowTextBk == CLR_NONE)
    		dc.SetBkMode(iOldBkMode);
    	dc.SelectObject(pOldFont);
    	dc.SetTextColor(crOldTextColor);*/
}