Beispiel #1
0
CString CInput::GetInput()
{
	char szInputBuffer[512]; // Buffer MUST be 3 or more (input char, \n, \0)
	CString strInputString;

	// Wait for input from the console
	fgets(szInputBuffer, sizeof(szInputBuffer), stdin);

	// Do we have anything in the input?
	if(szInputBuffer[0] != '\n')
	{
		// Append the input to the input string
		strInputString += szInputBuffer;

		// Get the input string length
		size_t sLength = strInputString.GetLength();

		// Is this the last of the input?
		if(strInputString[sLength - 1] == '\n')
		{
#ifdef _WIN32
			// Replace '\n' with '\0'
			strInputString.Truncate(sLength - 1);
#else
			// Replace '\r\n' with '\0'
			strInputString.Truncate(sLength - 2);
#endif

			// Return the input
			return strInputString;
		}
	}
	return strInputString;
}
Beispiel #2
0
bool GitAdminDir::HasAdminDir(const CString& path, bool bDir, CString* ProjectTopDir, bool* IsAdminDirPath)
{
	if (path.IsEmpty())
		return false;
	CString sDirName = path;
	if (!bDir)
	{
		// e.g "C:\"
		if (path.GetLength() <= 3)
			return false;
		sDirName.Truncate(max(0, sDirName.ReverseFind(L'\\')));
	}

	// a .git dir or anything inside it should be left out, only interested in working copy files -- Myagi
	int n = 0;
	for (;;)
	{
		n = sDirName.Find(L"\\.git", n);
		if (n < 0)
			break;

		// check for actual .git dir (and not .gitignore or something else), continue search if false match
		n += 5;
		if (sDirName[n] == L'\\' || sDirName[n] == 0)
		{
			if (IsAdminDirPath)
				*IsAdminDirPath = true;
			return false;
		}
	}

	for (;;)
	{
		if (CGit::GitPathFileExists(sDirName + L"\\.git"))
		{
			if(ProjectTopDir)
			{
				*ProjectTopDir=sDirName;
				// Make sure to add the trailing slash to root paths such as 'C:'
				if (sDirName.GetLength() == 2 && sDirName[1] == L':')
					(*ProjectTopDir) += L'\\';
			}
			return true;
		}
		else if (IsBareRepo(sDirName))
			return false;

		int x = sDirName.ReverseFind(L'\\');
		if (x < 2)
			break;

		sDirName.Truncate(x);
		// don't check for \\COMPUTERNAME\.git
		if (sDirName[0] == L'\\' && sDirName[1] == L'\\' && sDirName.Find(L'\\', 2) < 0)
			break;
	}

	return false;
}
Beispiel #3
0
// Takes access to a string, default peek false to move a line from the buffer to the string, and default CP_ACP to read ASCII text
// Looks for bytes like "line\r\n" in the buffer, and moves them from the buffer to the string, throwing away the "\r\n" part
// Returns true if a line was found and moved from the buffer to the string, false if there isn't a '\n' in the buffer right now
BOOL CBuffer::ReadLine(CString& strLine, BOOL bPeek, UINT nCodePage)
{
    // Empty the string, making it blank
    strLine.Empty();

    // If this buffer is empty, tell the caller we didn't find a complete line
    if ( ! m_nLength ) return FALSE;

    // Scan down each byte in the buffer
    DWORD nLength;
    for ( nLength = 0 ; nLength < m_nLength ; nLength++ )
    {
        // If the byte at this length is the newline character '\n', exit the loop
        if ( m_pBuffer[ nLength ] == '\n' ) break;
    }

    // If the loop didn't find a '\n' and instead stopped because nLength grew to equal m_nLength
    if ( nLength >= m_nLength ) return FALSE; // There isn't an '\n' in the buffer, tell the caller we didn't find a complete line

    // Convert the nLength ASCII characters in the buffer into wide characters in strLine
    int nWide = MultiByteToWideChar( nCodePage, 0, (LPCSTR)m_pBuffer, nLength, NULL, 0 );
    MultiByteToWideChar( nCodePage, 0, (LPCSTR)m_pBuffer, nLength, strLine.GetBuffer( nWide ), nWide );
    strLine.ReleaseBuffer( nWide );

    // Find the last carriage return '\r' character in the string
    int nCR = strLine.ReverseFind( '\r' );   // Find the distance to the last \r, "hello\r" would be 5
    if ( nCR >= 0 ) strLine.Truncate( nCR ); // Cut the string to that length, like "hello"

    // Now that the line has been copied into the string, remove it and the '\n' from the buffer
    if ( ! bPeek ) Remove( nLength + 1 ); // Unless we're peeking, then leave it in the buffer

    // Report that we found a line and moved it from the buffer to the string
    return TRUE;
}
void DlgRoomLayoutWindowProperty::OnEnChangeEditOffsetheight()
{
	// TODO:  如果该控件是 RICHEDIT 控件,它将不
	// 发送此通知,除非重写 CDialogEx::OnInitDialog()
	// 函数并调用 CRichEditCtrl().SetEventMask(),
	// 同时将 ENM_CHANGE 标志“或”运算到掩码中。

	// TODO:  在此添加控件通知处理程序代码
	auto& imp_ = *ImpUPtr_;

	CString num;
	EditOffsetHeight_.GetWindowText(num);

	if ( num.IsEmpty() )
	{
		imp_.OffsetHeightValid_ = false;
	}
	else
	{
		if ( num.GetLength() > 4 )
		{
			num.Truncate(4);
			EditOffsetHeight_.SetWindowText(num);
		}

		std::wstring str = num.GetBuffer();
		num.ReleaseBuffer();
		imp_.TmpWindowInfo_.OffsetHeight_ = static_cast<float>(std::stoi(str));

		imp_.OffsetHeightValid_ = true;
	}

	BtnOK_.EnableWindow( imp_.XValid_ && imp_.YValid_ && imp_.ZValid_ && imp_.OffsetHeightValid_ );
}
Beispiel #5
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int /*nCmdShow*/)
{
#ifdef _DEBUG
//     bkconsole console;
#endif

   // BkWinManager bkwinmgr;

    BkFontPool::SetDefaultFont(_T("���ו"), -12);

    CString strPath;

    GetModuleFileName((HMODULE)&__ImageBase, strPath.GetBuffer(MAX_PATH + 10), MAX_PATH);
    strPath.ReleaseBuffer();
    strPath.Truncate(strPath.ReverseFind(L'\\') + 1);
    strPath += L"res";

    BkResManager::SetResourcePath(strPath);

    BkSkin::LoadSkins(IDR_BK_SKIN_DEF);
    BkStyle::LoadStyles(IDR_BK_STYLE_DEF);
    BkString::Load(IDR_BK_STRING_DEF);

	CMainDlg dlg;

	HANDLE hEventQuit = NULL;
	HANDLE hSingleProcess = CreateEvent(NULL,FALSE,FALSE,L"quick serach");
	if (GetLastError() == ERROR_ALREADY_EXISTS)
	{
		SetEvent(hSingleProcess);
		goto Exit0;
	}

	KContextSingletion::GetInstance()->m_hInstance = hInstance;
	KContextSingletion::GetInstance()->m_threadPool.Init();

	KJobCreateIndextable* pJobCreateIndextable = new KJobCreateIndextable(NULL);
	KContextSingletion::GetInstance()->m_threadPool.PostJob(pJobCreateIndextable);

	hEventQuit = CreateEvent(NULL,FALSE,FALSE,NULL);
	KJobSingleProcess* pJobSingleProcess = new KJobSingleProcess(hSingleProcess,hEventQuit);
	KContextSingletion::GetInstance()->m_threadPool.PostJob(pJobSingleProcess);

	dlg.DoModal(NULL);

	SetEvent(hEventQuit);
	KContextSingletion::GetInstance()->m_threadPool.UnInit();

Exit0:
	if (hEventQuit != NULL)
	{
		CloseHandle(hEventQuit);
	}
	if (hSingleProcess != NULL)
	{
		CloseHandle(hSingleProcess);
	}

    return 0;
}
Beispiel #6
0
BOOL CBuffer::ReadLine(CString& strLine, UINT nCodePage, BOOL bPeek)
{
	strLine.Empty();

	DWORD nLength; for ( nLength = 0 ; nLength < m_nLength ; nLength++ )
	{
		if ( m_pBuffer[ nLength ] == '\n' ) break;
	}

	if ( nLength >= m_nLength ) return FALSE;

	int nWide = MultiByteToWideChar( nCodePage, 0, (LPCSTR)m_pBuffer, nLength, NULL, 0 );

	LPWSTR pszWide = new WCHAR[ nWide ];
	MultiByteToWideChar( nCodePage, 0, (LPCSTR)m_pBuffer, nLength, pszWide, nWide );
	strLine = CString( pszWide, nWide ); delete [] pszWide;

	int nCR = strLine.ReverseFind( '\r' );
#if _MSC_VER >= 1400
	if ( nCR >= 0 ) strLine.Truncate( nCR );
#else
	if ( nCR >= 0 ) strLine = strLine.Left( nCR );
#endif

	if ( ! bPeek ) Remove( nLength + 1 );

	return TRUE;
}
Beispiel #7
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int /*nCmdShow*/)
{
#ifdef _DEBUG
//     bkconsole console;
#endif

    BkWinManager bkwinmgr;

    BkFontPool::SetDefaultFont(_T("宋体"), -12);

    CString strPath;

    GetModuleFileName((HMODULE)&__ImageBase, strPath.GetBuffer(MAX_PATH + 10), MAX_PATH);
    strPath.ReleaseBuffer();
    strPath.Truncate(strPath.ReverseFind(L'\\') + 1);
    strPath += L"res";

    BkResManager::SetResourcePath(strPath);

    BkSkin::LoadSkins(IDR_BK_SKIN_DEF);
    BkStyle::LoadStyles(IDR_BK_STYLE_DEF);
    BkString::Load(IDR_BK_STRING_DEF);

    CDemoMainDlg dlg;

    dlg.DoModal(NULL);

    return 0;
}
Beispiel #8
0
bool CPPageBase::FillComboToolTip(CComboBox& comboBox, TOOLTIPTEXT* pTTT)
{
    bool bNeedTooltip = false;

    CDC* pDC = comboBox.GetDC();
    CFont* pFont = comboBox.GetFont();
    CFont* pOldFont = pDC->SelectObject(pFont);

    TEXTMETRIC tm;
    pDC->GetTextMetrics(&tm);

    CRect comboBoxRect;
    comboBox.GetWindowRect(comboBoxRect);
    comboBoxRect.right -= GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXEDGE);

    int i = comboBox.GetCurSel();
    CString str;
    comboBox.GetLBText(i, str);
    CSize textSize;
    textSize = pDC->GetTextExtent(str);
    pDC->SelectObject(pOldFont);
    comboBox.ReleaseDC(pDC);
    textSize.cx += tm.tmAveCharWidth;

    if (textSize.cx > comboBoxRect.Width()) {
        bNeedTooltip = true;
        if (str.GetLength() > _countof(pTTT->szText) - 1) {
            str.Truncate(_countof(pTTT->szText) - 1);
        }
        _tcscpy_s(pTTT->szText, str);
        pTTT->hinst = nullptr;
    }

    return bNeedTooltip;
}
CString AbstractNewDialog::GetName(void)
{
  CString name = m_name;
  int ext = name.Find('.');
  if (ext != -1)
    name.Truncate(ext);
  return name;
}
Beispiel #10
0
// mklink /D "C:\existingFolder\Link" "C:\Target"
// mklink /D "C:\existingFolder\Link\" "C:\Target\"
// The ending slash is optional. The parent directory of the link must exist.
bool BrainUtil::MakeLink(const CString& link, const CString& target, bool bIsDirectory/* = true*/)
{
    CString temLink = link;
    CString temTarget = target;

    // delete the last '\'
    WCHAR lastChar = temLink.GetAt(temLink.GetLength() - 1);
    if(lastChar == _T('\\'))
        temLink.Truncate(temLink.GetLength() - 1); 

    if(DoesFileorFolderExist(temLink))
    {
        // Delete the link
        // For links to directories: rmdir linkname
        // For links to files: del linkname
        CString tmpCmd;
        tmpCmd.Format(_T("rmdir \"%s\""), temLink.GetBuffer());
        RunSystemCommand(tmpCmd);

        if(DoesFileorFolderExist(temLink)) // If still exist it might be a file link
        {
            tmpCmd.Format(_T("del \"%s\""), temLink.GetBuffer());
            RunSystemCommand(tmpCmd);
        }

        if(DoesFileorFolderExist(temLink))// check again
        {
            DATA_ASSERT(false); 
            return false;
        }
    }
    else
    {
        CString folderFullName = GetParentFolderName(link);
        if(!DoesFileorFolderExist(folderFullName))
        {
            bool bRet = CreateFolder(folderFullName); // Create the parent directory tree.
            if(!bRet)
                return false;
        }
    }

    CString cmd;
    if(bIsDirectory)
        cmd.Format(_T("mklink /D \"%s\" \"%s\""), temLink.GetBuffer(), temTarget.GetBuffer());
    else
        cmd.Format(_T("mklink \"%s\" \"%s\""), temLink.GetBuffer(), temTarget.GetBuffer());

    int ret = _wsystem(cmd.GetBuffer());
    DATA_ASSERT(0 == ret);
    bool bSucc = DoesFileorFolderExist(link);
    return bSucc;
}
bool CGitIgnoreList::IsIgnore(CString str, const CString& projectroot, bool isDir)
{
	str.Replace(_T('\\'),_T('/'));

	if (!str.IsEmpty() && str[str.GetLength() - 1] == _T('/'))
		str.Truncate(str.GetLength() - 1);

	int ret;
	ret = CheckIgnore(str, projectroot, isDir);
	while (ret < 0)
	{
		int start = str.ReverseFind(_T('/'));
		if(start < 0)
			return (ret == 1);

		str.Truncate(start);
		ret = CheckIgnore(str, projectroot, isDir);
	}

	return (ret == 1);
}
Beispiel #12
0
// GetParentFolderName(_T("C:\\RootFolder\\ChildFolder\\")); return C:\RootFolder\
// GetParentFolderName(_T("C:\\RootFolder\\ChildFolder\\readme.txt")); return C:\RootFolder\ChildFolder\
// GetParentFolderName(_T("RootFolder\\")); return .\
// The last char is always '\' in the return value.
CString GetParentFolderName(const CString& fileOrFolderName)
{
    CString tempName = fileOrFolderName;
    WCHAR lastChar = tempName.GetAt(tempName.GetLength() - 1);
    if(lastChar == _T('\\'))
        tempName.Truncate(tempName.GetLength() - 1); // delete the last '\'

    int lastPos = tempName.ReverseFind(_T('\\'));
    CString folderName(_T(".\\")); // current directory
    if(lastPos != -1)
        folderName = tempName.Left(lastPos + 1);

    return folderName;
}
Beispiel #13
0
CString sysGetUserName (void)

//	sysGetUserName
//
//	Returns the name of the currently logged-on user

	{
	CString sName;
	DWORD dwLen = 256;
	char *pPos = sName.GetWritePointer(dwLen);

	::GetUserName(pPos, &dwLen);
	sName.Truncate(lstrlen(pPos));

	return sName;
	}
Beispiel #14
0
void Util::MakeValidUserName(CString& strName, BOOL bWPN, WORD wID)
{

	strName.Replace(" ", " "); // replace normal space with nonbreaking space
	
	CString strBase = strName;
	Util::BaseName(strBase);

	if(strBase.GetLength() > 36){

		//strBase = strBase.Left(39);
		strBase.Truncate(39);
		int nLen = strBase.GetLength()-1;
		while(nLen > 35){

			if(!_istdigit(strBase[nLen])){

				strBase.SetAt(nLen, (char)(rand()%9 + 48));
			}
			nLen--;
		}
	}

	// Verify the last 3 digits are numbers
	int nDigits = 0, i = strBase.GetLength() - 1;
	for(nDigits = 0; i > 0 && nDigits < 3; i--){

		if(_istdigit(strBase[i])) nDigits ++;
		else break;
	}
	while(nDigits < 3){

		strBase += Util::Formatint(rand() % 9);
		nDigits++;
	}


	if(bWPN){

		strName.Format("%s_%05d", strBase, wID);
	}

	else{

		strName.Format("%s_%05d", strBase, rand() % 99999);
	}
}
void CTableTitle::ExtractOHReplayFrameNumber(const CString *s) {
  if (s->GetLength() < 8) {
    return;
  }
  if (RightCharacter(*s) != ']') {
    return;
  }
  if (RightCharacter(*s, 7) != '[') {
    return;
  }
  // Title-format: #################[003141]
  // Extract frame-number
  int length = s->GetLength();
  int start_pos = length - 7;
  CString framenumber = s->Mid(start_pos);
  framenumber.Truncate(6);
  _ohreplay_framenumber = atoi(framenumber);
}
Beispiel #16
0
CString FormatNumber(CString szNumber, bool bNoFractionalDigits /*= true*/)
{
    CString ret;

    int nChars = GetNumberFormat(LOCALE_USER_DEFAULT, 0, szNumber, nullptr, nullptr, 0);
    GetNumberFormat(LOCALE_USER_DEFAULT, 0, szNumber, nullptr, ret.GetBuffer(nChars), nChars);
    ret.ReleaseBuffer();

    if (bNoFractionalDigits) {
        TCHAR szNumberFractionalDigits[2] = {0};
        GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDIGITS, szNumberFractionalDigits, _countof(szNumberFractionalDigits));
        int nNumberFractionalDigits = _tcstol(szNumberFractionalDigits, nullptr, 10);
        if (nNumberFractionalDigits) {
            ret.Truncate(ret.GetLength() - nNumberFractionalDigits - 1);
        }
    }

    return ret;
}
Beispiel #17
0
void GrailMain (void)
	{
	ALERROR error;
	CTextOut Output;
	CLabyrinth Lab(&Output);

	//	Boot

	printf("Grail Language v1.0\n\n");

	if (error = Lab.Boot())
		{
		printf("%s\n", Lab.GetLastErrorMsg().GetASCIIZPointer());
		return;
		}

	printf("Grail ready\n\n");

	//	Command loop

	while (true)
		{
		//	Get user input

		CString sInput;
		printf(": ");
		gets(sInput.GetWritePointer(1024));
		sInput.Truncate(lstrlen(sInput.GetASCIIZPointer()));

		//	If this is the quit command, we're done

		if (strEquals(sInput, CONSTLIT("quit")))
			break;

		//	Process the command

		}

	//	Done

	Lab.Shutdown();
	printf("End session.");
	}
Beispiel #18
0
void CBabelData::CleanUp (void)

//	CleanUp
//
//	Deallocates appropriately but does not reset the member
//	variables.

{
    switch (m_Type)
    {
    case dtNil:
    case dtInteger:
        break;

    case dtString:
    case dtCode:
    {
        CString *pString = (CString *)&m_dwData;
        pString->Truncate(0);
        break;
    }

    case dtList:
    {
        ListData *pData = (ListData *)m_dwData;
        if (--pData->iRefCount == 0)
            delete pData;
        break;
    }

    case dtStructure:
    {
        StructData *pData = (StructData *)m_dwData;
        if (--pData->iRefCount == 0)
            delete pData;
        break;
    }

    default:
        ASSERT(false);
    }
}
Beispiel #19
0
void CPPageFullscreen::OnEndlabeleditList(NMHDR* pNMHDR, LRESULT* pResult)
{
	LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
	LV_ITEM* pItem = &pDispInfo->item;
	*pResult = FALSE;
	if (!m_list.m_fInPlaceDirty) {
		return;
	}
	if (pItem->iItem < 0) {
		return;
	}
	switch (pItem->iSubItem) {
		case COL_SRR:
			if (pItem->lParam >= 0) {
				m_iSeldm[pItem->iItem] = m_iSel = pItem->lParam;
				m_list.SetItemText(pItem->iItem, pItem->iSubItem, pItem->pszText);
			}
			break;
		case COL_VFR_F:
		case COL_VFR_T:
			if (pItem->pszText) {
				CString str = pItem->pszText;
				int dotpos = str.Find('.');
				if (dotpos >= 0 && str.GetLength() - dotpos > 4) {
					str.Truncate(dotpos + 4);
				}
				float f = min(max(_tstof(str), 1.0), 125.999);
				str.Format(_T("%.3f"), f);
				m_list.SetItemText(pItem->iItem, pItem->iSubItem, str);
			}
			break;
	}

	*pResult = TRUE;

	if (*pResult) {
		SetModified();
	}
}
void CMediaHubSetting::OnBnClickedMediaHubButSelect() {
   
    // Get the default browse folder to the current path of videos       
    CString path;
    GetDlgItemText(IDC_MEDIA_HUB_EDIT_FOLDER, path);
    
    WCHAR* t = toWideChar(getMediaHubDefault().c_str());
    CString mediaHub = t;
    CString mediaDir = path;
    int found = mediaDir.Find(mediaHub);
    if (found > -1) {
        mediaDir.Truncate(found);
    }

    CString caption;
    caption.LoadString(IDS_MEDIA_HUB_TITLE_PICKER);
    
    // Open the browse for folder window (modal)
    wstring newPath;
    if ( browseFolder(newPath, mediaDir.GetBuffer(), caption.GetBuffer(), GetSafeHwnd()) ) {
        // Update the UI label and save the new path
        if (newPath.find_last_of(L"\\") == newPath.length() -1) {
            newPath = newPath.substr(0, newPath.length() -1);
        }
        newPath.append(t);
        SetDlgItemText(IDC_MEDIA_HUB_EDIT_FOLDER, newPath.c_str());     

        // check if the folder is different to the default one we enable the "reset" button
        StringBuffer t; t.convert(newPath.c_str());
        if (t != getFullMediaHubDefault()) {
            GetDlgItem(IDC_MEDIA_HUB_BUT_RESET)->EnableWindow(TRUE);
        } else {
            GetDlgItem(IDC_MEDIA_HUB_BUT_RESET)->EnableWindow(FALSE);
        }

    }   
    delete [] t;
}
void KAppModule::_InitUIResource()
{

    //BkFontPool::SetDefaultFont(BkString::Get(IDS_APP_FONT), -12);

    if ( TRUE /*_CmdLine.HasParam(L"{69DD4969-E6C4-42d9-A508-105DDA13CE40}")*/)
    {
        CString strPath;

        GetModuleFileName((HMODULE)&__ImageBase, strPath.GetBuffer(MAX_PATH + 10), MAX_PATH);
        strPath.ReleaseBuffer();
        strPath.Truncate(strPath.ReverseFind(L'\\') + 1);
        strPath += L"res\\safeflow";

        if ( PathFileExists(strPath) )
            BkResManager::SetResourcePath(strPath);
    }

    BkFontPool::SetDefaultFont(_T("宋体"), -12);

    BkSkin::LoadSkins(IDR_BK_SKIN_DEF);
    BkStyle::LoadStyles(IDR_BK_STYLE_DEF);
    BkString::Load(IDR_BK_STRING_DEF);
}
Beispiel #22
0
// Attaches the API: loads the DLL
// Returns:
//		IPOD_ERR_OK				when successful
//		IPOD_ERR_DLL_NOT_FOUND	when the iTunesMobileDevice.dll could not be loaded
//
t_iPodError CiPoTApi::AttachDLL()
{
	HKEY hSetting = NULL;
	DWORD length = 0;
	CString path;
	int pos;
	t_MachError ret;
	t_AMDeviceNotification *notif; 

	if (m_iPodState == IPOD_STATE_NO_DLL) {
		if (m_pCoreFoundationPath == NULL) {
			if (::RegCreateKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Apple Inc.\\Apple Application Support"), &hSetting) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			if (::RegQueryValueEx(hSetting, _T("InstallDir"), NULL, NULL, NULL, &length) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			m_pCoreFoundationPath = new char[length+19+1]; // \CoreFoundation.dll = 19
			::RegQueryValueEx(hSetting, _T("InstallDir"), NULL, NULL, (LPBYTE)m_pCoreFoundationPath, &length);
			::RegCloseKey(hSetting);


			// Adds the folder to the current system path:	
			path.GetEnvironmentVariable("PATH");
			path = (path + ";") + m_pCoreFoundationPath;
			SetEnvironmentVariable("PATH", path);

			if (m_pCoreFoundationPath[lstrlen(m_pCoreFoundationPath)-1] != '\\')
				strcat(m_pCoreFoundationPath, "\\");
			strcat(m_pCoreFoundationPath, "CoreFoundation.dll");
		}
		
		if (m_piTunesMobileDevicePath == NULL) {
			// Adds iTunesMobileDevice.dll folder to the path, from the registry:
			if (::RegCreateKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Apple Inc.\\Apple Mobile Device Support\\Shared"), &hSetting) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			if (::RegQueryValueEx(hSetting, _T("iTunesMobileDeviceDLL"), NULL, NULL, NULL, &length) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			m_piTunesMobileDevicePath = new char[length+1];
			::RegQueryValueEx(hSetting, _T("iTunesMobileDeviceDLL"), NULL, NULL, (LPBYTE)m_piTunesMobileDevicePath, &length);
			::RegCloseKey(hSetting);

			// Adds the folder to the current system path:	
			path.GetEnvironmentVariable("PATH");
			path = (path + ";") + m_piTunesMobileDevicePath;
			pos = path.ReverseFind('\\');
			if (pos >= 0)
				path.Truncate(pos);
			SetEnvironmentVariable("PATH", path);
		}

		// Loads the iTunesMobileDevice DLL routines
		m_iTunesDll = LoadLibrary(m_piTunesMobileDevicePath);
		if (m_iTunesDll) {
			AMDeviceNotificationSubscribe = (tf_AMDeviceNotificationSubscribe)GetProcAddress(m_iTunesDll, "AMDeviceNotificationSubscribe");
			AMDeviceConnect = (tf_AMDeviceConnect)GetProcAddress(m_iTunesDll, "AMDeviceConnect");
			AMDeviceDisconnect = (tf_AMDeviceDisconnect)GetProcAddress(m_iTunesDll, "AMDeviceDisconnect");
			AMDeviceIsPaired = (tf_AMDeviceIsPaired)GetProcAddress(m_iTunesDll, "AMDeviceIsPaired");
			AMDeviceValidatePairing = (tf_AMDeviceValidatePairing)GetProcAddress(m_iTunesDll, "AMDeviceValidatePairing");
			AMDeviceStartSession = (tf_AMDeviceStartSession)GetProcAddress(m_iTunesDll, "AMDeviceStartSession");
			AMDeviceStartService = (tf_AMDeviceStartService)GetProcAddress(m_iTunesDll, "AMDeviceStartService");
			AMDeviceStopSession = (tf_AMDeviceStopSession)GetProcAddress(m_iTunesDll, "AMDeviceStopSession");
			AFCConnectionOpen = (tf_AFCConnectionOpen)GetProcAddress(m_iTunesDll, "AFCConnectionOpen");
			AFCDeviceInfoOpen = (tf_AFCDeviceInfoOpen)GetProcAddress(m_iTunesDll, "AFCDeviceInfoOpen");
			AFCDirectoryOpen = (tf_AFCDirectoryOpen)GetProcAddress(m_iTunesDll, "AFCDirectoryOpen");
			AFCDirectoryRead = (tf_AFCDirectoryRead)GetProcAddress(m_iTunesDll, "AFCDirectoryRead");
			AFCDirectoryClose = (tf_AFCDirectoryClose)GetProcAddress(m_iTunesDll, "AFCDirectoryClose");
			AFCFileInfoOpen = (tf_AFCFileInfoOpen)GetProcAddress(m_iTunesDll, "AFCFileInfoOpen");
			AFCKeyValueRead = (tf_AFCKeyValueRead)GetProcAddress(m_iTunesDll, "AFCKeyValueRead");
			AFCKeyValueClose = (tf_AFCKeyValueClose)GetProcAddress(m_iTunesDll, "AFCKeyValueClose");
			AFCFileRefOpen = (tf_AFCFileRefOpen)GetProcAddress(m_iTunesDll, "AFCFileRefOpen");
			AFCFileRefClose = (tf_AFCFileRefClose)GetProcAddress(m_iTunesDll, "AFCFileRefClose");
			AFCFileRefRead = (tf_AFCFileRefRead)GetProcAddress(m_iTunesDll, "AFCFileRefRead");
			AFCFileRefWrite = (tf_AFCFileRefWrite)GetProcAddress(m_iTunesDll, "AFCFileRefWrite");
			AFCRemovePath = (tf_AFCRemovePath)GetProcAddress(m_iTunesDll, "AFCRemovePath");
			AFCDirectoryCreate = (tf_AFCDirectoryCreate)GetProcAddress(m_iTunesDll, "AFCDirectoryCreate");
			AFCRenamePath = (tf_AFCRenamePath)GetProcAddress(m_iTunesDll, "AFCRenamePath");
		} else
			return IPOD_ERR_DLL_NOT_FOUND;

		// Loads the CoreFoundation DLL routines
		m_CoreFoundationDll = LoadLibrary(m_pCoreFoundationPath);
		if (m_CoreFoundationDll) {
					 _CFStringMakeConstantString = (tf_CFStringMakeConstantString) GetProcAddress(m_CoreFoundationDll, "__CFStringMakeConstantString");
					 CFWriteStreamCreateWithFile = (tf_CFWriteStreamCreateWithFile)GetProcAddress(m_CoreFoundationDll, "CFWriteStreamCreateWithFile");
           CFReadStreamCreateWithFile = (tf_CFReadStreamCreateWithFile)GetProcAddress(m_CoreFoundationDll, "CFReadStreamCreateWithFile");
           CFStringCreateWithCString = (tf_CFStringCreateWithCString)GetProcAddress(m_CoreFoundationDll, "CFStringCreateWithCString");
           CFURLCreateWithFileSystemPath = (tf_CFURLCreateWithFileSystemPath)GetProcAddress(m_CoreFoundationDll, "CFURLCreateWithFileSystemPath");
           CFReadStreamOpen = (tf_CFReadStreamOpen)GetProcAddress(m_CoreFoundationDll, "CFReadStreamOpen");
           CFWriteStreamOpen = (tf_CFWriteStreamOpen)GetProcAddress(m_CoreFoundationDll, "CFWriteStreamOpen");
           CFPropertyListCreateFromStream = (tf_CFPropertyListCreateFromStream)GetProcAddress(m_CoreFoundationDll, "CFPropertyListCreateFromStream");
           CFReadStreamClose = (tf_CFReadStreamClose)GetProcAddress(m_CoreFoundationDll, "CFReadStreamClose");
           CFPropertyListIsValid = (tf_CFPropertyListIsValid)GetProcAddress(m_CoreFoundationDll, "CFPropertyListIsValid");
           CFPropertyListWriteToStream = (tf_CFPropertyListWriteToStream)GetProcAddress(m_CoreFoundationDll, "CFPropertyListWriteToStream");
           CFWriteStreamClose = (tf_CFWriteStreamClose)GetProcAddress(m_CoreFoundationDll, "CFWriteStreamClose");
           CFRelease = (tf_CFRelease)GetProcAddress(m_CoreFoundationDll, "CFRelease");
           CFURLCreateDataAndPropertiesFromResource = (tf_CFURLCreateDataAndPropertiesFromResource)GetProcAddress(m_CoreFoundationDll, "CFURLCreateDataAndPropertiesFromResource");
           CFPropertyListCreateFromXMLData = (tf_CFPropertyListCreateFromXMLData)GetProcAddress(m_CoreFoundationDll, "CFPropertyListCreateFromXMLData");
           CFPropertyListCreateXMLData = (tf_CFPropertyListCreateXMLData)GetProcAddress(m_CoreFoundationDll, "CFPropertyListCreateXMLData");
           CFURLWriteDataAndPropertiesToResource = (tf_CFURLWriteDataAndPropertiesToResource)GetProcAddress(m_CoreFoundationDll, "CFURLWriteDataAndPropertiesToResource");
            bCanTranslatePLIST = true;
		} else
			return IPOD_ERR_DLL_NOT_FOUND;
		m_iPodState = IPOD_STATE_UNCONNECTED;
	}
	// Registers the static notification call-back method
	ret = AMDeviceNotificationSubscribe(&CiPoTApi::NotificationHandler, 0, 0, 0, &notif);
	return (ret == MDERR_OK) ? IPOD_ERR_OK : IPOD_IPOD_NOT_FOUND;
}
Beispiel #23
0
void CUploadsCtrl::PaintFile(CDC& dc, const CRect& rcRow, CUploadQueue* /*pQueue*/, CUploadFile* pFile, int nPosition, BOOL bFocus)
{
	ASSUME_LOCK( Transfers.m_pSection );

	CUploadTransfer* pTransfer = pFile->GetActive();
	int nFlagImage = Flags.GetFlagIndex( pTransfer->m_sCountry );
	COLORREF crNatural		= CoolInterface.m_crWindow;
	COLORREF crBack			= pFile->m_bSelected ? CoolInterface.m_crHighlight : crNatural;
	COLORREF crLeftAligned	= crBack;
	COLORREF crBorder		= pFile->m_bSelected ? CoolInterface.m_crFragmentBorderSelected : CoolInterface.m_crFragmentBorder;

	dc.SetBkColor( crBack );
	dc.SetBkMode( OPAQUE );
	
	if ( pFile->m_bSelected )
		dc.SetTextColor( CoolInterface.m_crHiText );
	else if ( pTransfer == NULL || pTransfer->m_nState == upsNull )
		dc.SetTextColor( CoolInterface.m_crDisabled );
	else
		dc.SetTextColor( CoolInterface.m_crText );
	
	int nTextLeft = rcRow.right, nTextRight = rcRow.left;
	HDITEM pColumn = {};
	
	pColumn.mask = HDI_FORMAT | HDI_LPARAM;

	for ( int nColumn = 0 ; m_wndHeader.GetItem( nColumn, &pColumn ) ; nColumn++ )
	{
		CString strText;
		CRect rcCell;
		
		m_wndHeader.GetItemRect( nColumn, &rcCell );
		rcCell.left		+= rcRow.left;
		rcCell.right	+= rcRow.left;
		rcCell.top		= rcRow.top;
		rcCell.bottom	= rcRow.bottom;
		
		crLeftAligned = ( rcRow.left == rcCell.left ? crNatural : crBack ) ;

		switch ( pColumn.lParam )
		{
		case UPLOAD_COLUMN_TITLE:
			dc.FillSolidRect( rcCell.left, rcCell.top, 24, rcCell.Height(), crLeftAligned );
			rcCell.left += 24;
			dc.FillSolidRect( rcCell.left, rcCell.bottom - 1, 16, 1, crLeftAligned );
			ShellIcons.Draw( &dc, ShellIcons.Get( ( lstrcmpi(
				PathFindExtension( pFile->m_sPath ), _T(".partial") ) ?
				pFile->m_sPath : pFile->m_sName ), 16 ), 16,
				rcCell.left, rcCell.top, crBack, pFile->m_bSelected );
			rcCell.left += 16;
			dc.FillSolidRect( rcCell.left, rcCell.top, 1, rcCell.Height(), crLeftAligned );
			rcCell.left += 1;
			strText = pFile->m_sName;
			break;
			
		case UPLOAD_COLUMN_USER:
			if ( pTransfer == NULL )
				strText.Empty();
			else if ( pTransfer->m_sRemoteNick.IsEmpty() )
				strText = pTransfer->m_sAddress;
			else
				strText = pTransfer->m_sRemoteNick + _T(" (") + pTransfer->m_sAddress + _T(")");
			break;
			
		case UPLOAD_COLUMN_SIZE:
			strText = Settings.SmartVolume( pFile->m_nSize );
			break;
			
		case UPLOAD_COLUMN_PROGRESS:
			dc.Draw3dRect( &rcCell, crBack, crBack );
			rcCell.DeflateRect( 1, 1 );
			dc.Draw3dRect( &rcCell, crBack, crBack );
			rcCell.DeflateRect( 0, 1 );
			dc.Draw3dRect( &rcCell, crBorder, crBorder );
			rcCell.DeflateRect( 1, 1 );
			CFragmentBar::DrawUpload( &dc, &rcCell, pFile, crNatural );
			break;
			
		case UPLOAD_COLUMN_SPEED:
			if ( pTransfer == NULL || pTransfer->m_nState == upsNull )
				LoadString( strText, IDS_STATUS_COMPLETED );
			else if ( pTransfer->m_nProtocol == PROTOCOL_BT )
			{
				CUploadTransferBT* pBT = (CUploadTransferBT*)pTransfer;
				
				if ( ! pBT->m_bInterested )
					LoadString( strText, IDS_STATUS_UNINTERESTED );
				else if ( pBT->m_bChoked )
					LoadString( strText, IDS_STATUS_CHOKED );
				else
				{
					DWORD nSpeed = pTransfer->GetMeasuredSpeed();
					if ( nSpeed )
						strText = Settings.SmartSpeed( nSpeed );
				}
			}
			else if ( nPosition > 0 )
			{
				CString strQ;
				LoadString( strQ, IDS_STATUS_Q );
				strText.Format( _T("%s %i"), (LPCTSTR)strQ, nPosition );
			}
			else
			{
				DWORD nSpeed = pTransfer->GetMeasuredSpeed();
				if ( nSpeed )
					strText = Settings.SmartSpeed( nSpeed );
				else
					LoadString( strText, IDS_STATUS_NEXT );
			}
			break;
			
		case UPLOAD_COLUMN_CLIENT:
			if ( pTransfer != NULL ) strText = pTransfer->m_sUserAgent;
			break;
		case UPLOAD_COLUMN_RATING:
			strText.Format(_T("%u"), pTransfer->m_nUserRating );
			break;
		case UPLOAD_COLUMN_COUNTRY:
			dc.FillSolidRect( rcCell.left, rcCell.top, 20, rcCell.Height(), crBack );
			rcCell.left += 2;
			if ( nFlagImage >= 0 )
				Flags.Draw( nFlagImage, dc.GetSafeHdc(), rcCell.left, rcCell.top + 2, CLR_NONE, CLR_DEFAULT, pFile->m_bSelected ? ILD_SELECTED : ILD_NORMAL );

			rcCell.left += 16;
			dc.FillSolidRect( rcCell.left, rcCell.top, 1, rcCell.Height(), crNatural );

			strText = pTransfer->m_sCountry;
			break;
		}
		
		nTextLeft	= min( (LONG)nTextLeft, rcCell.left );
		nTextRight	= max( (LONG)nTextRight, rcCell.right );
		
		if ( pColumn.lParam == UPLOAD_COLUMN_PROGRESS ) continue;
		
		if ( rcCell.Width() < 8 ) strText.Empty();
		
		if ( dc.GetTextExtent( strText ).cx > rcCell.Width() - 8 )
		{
			while ( dc.GetTextExtent( strText + _T('\x2026') ).cx > ( rcCell.Width() - 8 ) && strText.GetLength() > 0 )
			{
				strText.Truncate( strText.GetLength() - 1 );
			}
			
			if ( strText.GetLength() > 0 ) strText += _T('\x2026');
		}
		
		int nWidth		= dc.GetTextExtent( strText ).cx;
		int nPos	= 0;
		
		switch ( pColumn.fmt & LVCFMT_JUSTIFYMASK )
		{
		default:
			nPos = ( rcCell.left + 4 );
			break;
		case LVCFMT_CENTER:
			nPos = ( ( rcCell.left + rcCell.right ) / 2 ) - ( nWidth / 2 );
			break;
		case LVCFMT_RIGHT:
			nPos = ( rcCell.right - 4 - nWidth );
			break;
		}
		
		dc.SetBkColor( crBack );
		dc.ExtTextOut( nPos, rcCell.top + 2, ETO_CLIPPED|ETO_OPAQUE,
			&rcCell, strText, NULL );
	}
	
	if ( nTextRight < rcRow.right )
	{
		CRect rcBlank( nTextRight, rcRow.top, rcRow.right, rcRow.bottom );
		dc.FillSolidRect( &rcBlank, crBack );
	}
	
	if ( bFocus )
	{
		CRect rcFocus( nTextLeft, rcRow.top, max( (int)rcRow.right, nTextRight ), rcRow.bottom );
		dc.Draw3dRect( &rcFocus, CoolInterface.m_crHiBorder, CoolInterface.m_crHiBorder );
	}
}
Beispiel #24
0
void CUploadsCtrl::PaintQueue(CDC& dc, const CRect& rcRow, CUploadQueue* pQueue, BOOL bFocus)
{
	ASSUME_LOCK( UploadQueues.m_pSection );

	COLORREF crNatural	= CoolInterface.m_crWindow;
	COLORREF crBack		= pQueue->m_bSelected ? CoolInterface.m_crHighlight : crNatural;
	COLORREF crLeftAligned = crBack ;

	dc.SetBkColor( crBack );
	dc.SetBkMode( OPAQUE );
	
	if ( pQueue->m_bSelected )
		dc.SetTextColor( CoolInterface.m_crHiText );
	else
		dc.SetTextColor( CoolInterface.m_crText );
	
	int nTextLeft = rcRow.right, nTextRight = rcRow.left;
	HDITEM pColumn = {};
	
	pColumn.mask = HDI_FORMAT | HDI_LPARAM;
	
	dc.SelectObject( &CoolInterface.m_fntBold );
	
	for ( int nColumn = 0 ; m_wndHeader.GetItem( nColumn, &pColumn ) ; nColumn++ )
	{
		CString strText;
		CRect rcCell;
		
		m_wndHeader.GetItemRect( nColumn, &rcCell );
		rcCell.left		+= rcRow.left;
		rcCell.right	+= rcRow.left;
		rcCell.top		= rcRow.top;
		rcCell.bottom	= rcRow.bottom;

		crLeftAligned = ( rcRow.left == rcCell.left ? crNatural : crBack ) ;

		POINT ptHover;
		RECT  rcTick = { rcCell.left+2, rcCell.top+2, rcCell.left+14, rcCell.bottom-2 };
		GetCursorPos(&ptHover);
		ScreenToClient(&ptHover);

		switch ( pColumn.lParam )
		{
		case UPLOAD_COLUMN_TITLE:
			dc.FillSolidRect( rcCell.left, rcCell.bottom - 1, 32, 1, crLeftAligned );

			if ( pQueue->m_bExpanded )
			{
			CoolInterface.Draw( &dc, PtInRect(&rcTick,ptHover) ? IDI_MINUS_HOVER : IDI_MINUS,
					16, rcCell.left, rcCell.top, crLeftAligned );
			}
			else
			{
				CoolInterface.Draw( &dc, PtInRect(&rcTick,ptHover) ? IDI_PLUS_HOVER : IDI_PLUS,
					16, rcCell.left, rcCell.top, crLeftAligned );
			}

			rcCell.left += 16;
			if ( pQueue == UploadQueues.m_pTorrentQueue )
			{
				ImageList_DrawEx( m_gdiProtocols, PROTOCOL_BT, dc.GetSafeHdc(),
						rcCell.left, rcCell.top, 16, 16, crLeftAligned, CLR_DEFAULT, pQueue->m_bSelected ? ILD_SELECTED : ILD_NORMAL );
			}
			else if ( pQueue->m_nProtocols == ( 1 << PROTOCOL_HTTP ) )
			{
				ImageList_DrawEx( m_gdiProtocols, PROTOCOL_HTTP, dc.GetSafeHdc(),
						rcCell.left, rcCell.top, 16, 16, crLeftAligned, CLR_DEFAULT, pQueue->m_bSelected ? ILD_SELECTED : ILD_NORMAL );
			}
			else if ( pQueue->m_nProtocols == ( 1 << PROTOCOL_ED2K ) )
			{
				ImageList_DrawEx( m_gdiProtocols, PROTOCOL_ED2K, dc.GetSafeHdc(),
						rcCell.left, rcCell.top, 16, 16, crLeftAligned, CLR_DEFAULT, pQueue->m_bSelected ? ILD_SELECTED : ILD_NORMAL );
			}
			else
			{
				CoolInterface.Draw( &dc,
					pQueue->m_bExpanded ? IDI_FOLDER_OPEN : IDI_FOLDER_CLOSED, 16,
					rcCell.left, rcCell.top, crLeftAligned, pQueue->m_bSelected );
			}
			rcCell.left += 16;
			dc.FillSolidRect( rcCell.left, rcCell.top, 1, rcCell.Height(), crLeftAligned );
			rcCell.left += 1;
			
			strText = pQueue->m_sName;
			break;
			
		case UPLOAD_COLUMN_SIZE:
			if ( pQueue == UploadQueues.m_pTorrentQueue )
				strText.Format( _T("%u/%u"), pQueue->m_nMinTransfers, pQueue->m_nMaxTransfers ); //No. Clients was loaded into these variables
			else if ( pQueue != UploadQueues.m_pHistoryQueue )
				strText.Format( _T("%u/%u"), pQueue->GetTransferCount(), pQueue->GetQueuedCount() );
			break;
			
		case UPLOAD_COLUMN_SPEED:
			if ( pQueue != UploadQueues.m_pHistoryQueue )
				strText = Settings.SmartSpeed( pQueue->GetMeasuredSpeed() );
			break;
		}
		
		nTextLeft	= min( nTextLeft, (int)rcCell.left );
		nTextRight	= max( nTextRight, (int)rcCell.right );
		
		if ( rcCell.Width() < 8 ) strText.Empty();
		
		if ( dc.GetTextExtent( strText ).cx > rcCell.Width() - 8 )
		{
			while ( dc.GetTextExtent( strText + _T('\x2026') ).cx > ( rcCell.Width() - 8 ) && strText.GetLength() > 0 )
			{
				strText.Truncate( strText.GetLength() - 1 );
			}
			
			if ( strText.GetLength() > 0 ) strText += _T('\x2026');
		}
		
		int nWidth		= dc.GetTextExtent( strText ).cx;
		int nPosition	= 0;
		
		switch ( pColumn.fmt & LVCFMT_JUSTIFYMASK )
		{
		default:
			nPosition = ( rcCell.left + 4 );
			break;
		case LVCFMT_CENTER:
			nPosition = ( ( rcCell.left + rcCell.right ) / 2 ) - ( nWidth / 2 );
			break;
		case LVCFMT_RIGHT:
			nPosition = ( rcCell.right - 4 - nWidth );
			break;
		}
		
		dc.SetBkColor( crBack );
		dc.ExtTextOut( nPosition, rcCell.top + 2, ETO_CLIPPED|ETO_OPAQUE,
			&rcCell, strText, NULL );
	}
	
	if ( nTextRight < rcRow.right )
	{
		CRect rcBlank( nTextRight, rcRow.top, rcRow.right, rcRow.bottom );
		dc.FillSolidRect( &rcBlank, crBack );
	}
	
	dc.SelectObject( &CoolInterface.m_fntNormal );
	
	if ( bFocus )
	{
		CRect rcFocus( nTextLeft, rcRow.top, max( (int)rcRow.right, nTextRight ), rcRow.bottom );
		dc.Draw3dRect( &rcFocus, CoolInterface.m_crHiBorder, CoolInterface.m_crHiBorder );
	}
}
Beispiel #25
0
STDMETHODIMP CExtension::OpenFileFolder(BSTR aPath)
{
    DWORD fileAttr;
    CString path = aPath;

    fileAttr = GetFileAttributes(path);
    
    if (fileAttr == INVALID_FILE_ATTRIBUTES) {
        // file not found
        CString title, message;

        title.LoadStringW(IDS_ERROR);
        message.FormatMessage(IDS_FILE_DOES_NOT_EXIST, path);
        message += _T("\n\n");
        message.AppendFormat(IDS_PROMPT_OPEN_PARENT);

        MessageBeep(MB_ICONQUESTION);
        int retVal = MessageBox(NULL, message, title, MB_YESNO |
            MB_ICONQUESTION | MB_TASKMODAL);
        
        if (retVal == IDYES) {
                        
            int length, sepLastIndex;
            do { // loop to ensure we get rid of trailing '\' chars
                length = path.GetLength();            
                sepLastIndex = path.ReverseFind(_T('\\'));
                if (sepLastIndex > 0) {
                    path.Truncate(sepLastIndex);
                }
            } while ((sepLastIndex > 0) && (sepLastIndex == length - 1));

            fileAttr = GetFileAttributes(path);
    
            if (fileAttr == INVALID_FILE_ATTRIBUTES) {

                message.FormatMessage(IDS_FILE_DOES_NOT_EXIST, path);

                MessageBeep(MB_ICONEXCLAMATION);
                int retVal = MessageBox(NULL, message, title,
                    MB_ICONEXCLAMATION | MB_TASKMODAL);

                return S_OK;
            }

        } else {
            // user clicked 'No', so don't do anything else
            return S_OK;
        }
    }

    STARTUPINFO si;
    PROCESS_INFORMATION pi;   
    CString sCmdline;
        
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    sCmdline = _T("explorer ");
    if (!(fileAttr & FILE_ATTRIBUTE_DIRECTORY)) {
        // if this is not a directory, then we can actually select the file
        sCmdline += _T("/select,");
    }        
    sCmdline += _T("\"");
    sCmdline += path;
    sCmdline += _T("\"");
        
    CreateProcess(NULL, (LPWSTR)(LPCWSTR)sCmdline, NULL, NULL, 
        FALSE, 0, NULL, NULL, &si, &pi);
       
    // close handles right away because we don't need them
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );    
       
    return S_OK;
}
int CGitIgnoreList::CheckIgnore(const CString &path, const CString &projectroot, bool isDir)
{
	CString temp = CombinePath(projectroot, path);
	temp.Replace(_T('/'), _T('\\'));

	CStringA patha = CUnicodeUtils::GetMulti(path, CP_UTF8);
	patha.Replace('\\', '/');

	int type = 0;
	if (isDir)
	{
		type = DT_DIR;

		// strip directory name
		// we do not need to check for a .ignore file inside a directory we might ignore
		int i = temp.ReverseFind(_T('\\'));
		if (i >= 0)
			temp.Truncate(i);
	}
	else
	{
		type = DT_REG;

		int x = temp.ReverseFind(_T('\\'));
		if (x >= 2)
			temp.Truncate(x);
	}

	int pos = patha.ReverseFind('/');
	const char * base = (pos >= 0) ? ((const char*)patha + pos + 1) : patha;

	int ret = -1;

	CAutoReadLock lock(m_SharedMutex);
	while (!temp.IsEmpty())
	{
		CString tempOrig = temp;
		temp += _T("\\.git");

		if (CGit::GitPathFileExists(temp))
		{
			CString gitignore = temp;
			gitignore += _T("ignore");
			if ((ret = CheckFileAgainstIgnoreList(gitignore, patha, base, type)) != -1)
				break;

			CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
			CString wcglobalgitignore = adminDir;
			wcglobalgitignore += _T("info\\exclude");
			if ((ret = CheckFileAgainstIgnoreList(wcglobalgitignore, patha, base, type)) != -1)
				break;

			CString excludesFile = m_CoreExcludesfiles[adminDir];
			if (!excludesFile.IsEmpty())
				ret = CheckFileAgainstIgnoreList(excludesFile, patha, base, type);

			break;
		}

		temp += _T("ignore");
		if ((ret = CheckFileAgainstIgnoreList(temp, patha, base, type)) != -1)
			break;

		int found = 0;
		int i;
		for (i = temp.GetLength() - 1; i >= 0; i--)
		{
			if (temp[i] == _T('\\'))
				++found;

			if (found == 2)
				break;
		}

		temp.Truncate(i);
	}

	return ret;
}
int CGitIgnoreItem::FetchIgnoreList(const CString &projectroot, const CString &file, bool isGlobal)
{
	if (this->m_pExcludeList)
	{
		git_free_exclude_list(m_pExcludeList);
		m_pExcludeList = nullptr;
	}
	free(m_buffer);
	m_buffer = nullptr;

	this->m_BaseDir.Empty();
	if (!isGlobal)
	{
		CString base = file.Mid(projectroot.GetLength() + 1);
		base.Replace(_T('\\'), _T('/'));

		int start = base.ReverseFind(_T('/'));
		if(start > 0)
		{
			base.Truncate(start);
			this->m_BaseDir = CUnicodeUtils::GetMulti(base, CP_UTF8) + "/";
		}
	}

	if (CGit::GetFileModifyTime(file, &m_LastModifyTime))
		return -1;

	CAutoFile hfile = CreateFile(file,
			GENERIC_READ,
			FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
			nullptr,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			nullptr);

	if (!hfile)
		return -1 ;

	DWORD filesize = GetFileSize(hfile, nullptr);
	if (filesize == INVALID_FILE_SIZE)
		return -1;

	m_buffer = new BYTE[filesize + 1];
	if (!m_buffer)
		return -1;

	DWORD size = 0;
	if (!ReadFile(hfile, m_buffer, filesize, &size, nullptr))
	{
		free(m_buffer);
		m_buffer = nullptr;
		return -1;
	}
	m_buffer[size] = 0;

	if (git_create_exclude_list(&m_pExcludeList))
	{
		free(m_buffer);
		m_buffer = nullptr;
		return -1;
	}

	BYTE *p = m_buffer;
	int line = 0;
	for (DWORD i = 0; i < size; ++i)
	{
		if (m_buffer[i] == '\n' || m_buffer[i] == '\r' || i == (size - 1))
		{
			if (m_buffer[i] == '\n' || m_buffer[i] == '\r')
				m_buffer[i] = 0;

			if (p[0] != '#' && p[0] != 0)
				git_add_exclude((const char*)p, this->m_BaseDir, m_BaseDir.GetLength(), this->m_pExcludeList, ++line);

			p = m_buffer + i + 1;
		}
	}

	if (!line)
	{
		git_free_exclude_list(m_pExcludeList);
		m_pExcludeList = nullptr;
		free(m_buffer);
		m_buffer = nullptr;
	}

	return 0;
}
Beispiel #28
0
int DBInterface::CreateProjectSupplyTable(CString& project_supply_table)
{
	project_supply_table.Replace('\\','_');			// replace the backslash with _
	project_supply_table.Replace('\'', '_');		// replace the single quote "'" with _
	project_supply_table.Replace(' ', '_');
	project_supply_table.Replace('-', '_');
	project_supply_table.Replace('&', '_');
	project_supply_table.Replace('!', '_');
	project_supply_table.Replace('$', '_');
	project_supply_table.Replace('@', '_');
	project_supply_table.Replace('%', '_');
	project_supply_table.Replace('(', '_');
	project_supply_table.Replace(')', '_');
	project_supply_table.Replace('+', '_');
	project_supply_table.Replace('~', '_');
	project_supply_table.Replace('*', '_');
	project_supply_table.Replace('.', '_');
	project_supply_table.Replace(',', '_');
	project_supply_table.Replace('?', '_');
	project_supply_table.Replace(':', '_');
	project_supply_table.Replace(';', '_');
	project_supply_table.Replace('"', '_');
	project_supply_table.Replace('/', '_');
	project_supply_table.Replace('#', '_');

	//truncate the project name if its length is greater than 50
	if(project_supply_table.GetLength() > 50)
	{
		project_supply_table.Truncate(50);
	}

	CString table = "SUPPLY_TABLE_";
	table += project_supply_table;


	int ret;
	//create table IF NOT EXISTS table_name (track tinyint unsigned, query varchar(255), timestamp timestamp, index (track,timestamp), index(timestamp,track))
	CString query = "create table IF NOT EXISTS ";
	query += table;
	query += " (filename varchar(255),filesize int unsigned,hash varchar(33),ip int,port smallint unsigned,search_id int unsigned,timestamp timestamp,track tinyint unsigned,bitrate smallint, frequency int, duration int,index(search_id, timestamp,track),index(timestamp,search_id,track),index(hash,track),index(hash,track),index(track,hash))";

	ret = mysql_query(p_supply_conn, query);
	if(mysql_error(p_supply_conn)[0] != '\0')
	{
		CStdioFile file;
		if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0)
		{
			file.SeekToEnd();

			CString log;
			log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S");
			log += " CreateProjectSupplyTable(...) ";
			log += query;
			log += "\n";
			log += "Error: ";
			log += mysql_error(p_supply_conn);
			log += "\n\n";

			file.WriteString(log);
			file.Close();
		}
		else
		{
			DWORD error = GetLastError();
			MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK);
		}

		TRACE(mysql_error(p_supply_conn));
		TRACE("\n");
		TRACE(query);
		TRACE("\n");
	}
	return ret;
}
int CDownloadWithSources::AddSourceURLs(LPCTSTR pszURLs, BOOL bURN)
{
	CString strURLs( pszURLs );
	BOOL bQuote = FALSE;
	
	for ( int nScan = 0 ; nScan < strURLs.GetLength() ; nScan++ )
	{
		if ( strURLs[ nScan ] == '\"' )
		{
			bQuote = ! bQuote;
			strURLs.SetAt( nScan, ' ' );
		}
		else if ( strURLs[ nScan ] == ',' && bQuote )
		{
			strURLs.SetAt( nScan, '`' );
		}
	}
	
	strURLs += ',';
	
    int nCount = 0;
	for ( ; ; )
	{
		int nPos = strURLs.Find( ',' );
		if ( nPos < 0 ) break;
		
		CString strURL	= strURLs.Left( nPos );
		strURLs			= strURLs.Mid( nPos + 1 );
		strURL.TrimLeft();
		
		FILETIME tSeen = { 0, 0 };
		BOOL bSeen = FALSE;
		
		if ( _tcsistr( strURL, _T("://") ) != NULL )
		{
			nPos = strURL.ReverseFind( ' ' );
			
			if ( nPos > 0 )
			{
				CString strTime = strURL.Mid( nPos + 1 );
				strURL = strURL.Left( nPos );
				strURL.TrimRight();
				bSeen = TimeFromString( strTime, &tSeen );
			}
			
			for ( int nScan = 0 ; nScan < strURL.GetLength() ; nScan++ )
			{
				if ( strURL[ nScan ] == '`' ) strURL.SetAt( nScan, ',' );
			}
		}
		else
		{
			nPos = strURL.Find( ':' );
			if ( nPos < 1 ) continue;
			
			int nPort = 0;
			_stscanf( strURL.Mid( nPos + 1 ), _T("%i"), &nPort );
			strURL.Truncate( nPos );
			USES_CONVERSION;
			DWORD nAddress = inet_addr( T2CA( strURL ) );
			strURL.Empty();
			
			if ( ! Network.IsFirewalledAddress( &nAddress, TRUE ) && nPort != 0 && nAddress != INADDR_NONE )
			{
				if ( m_bSHA1 )
				{
					strURL.Format( _T("http://%s:%i/uri-res/N2R?%s"),
						(LPCTSTR)CString( inet_ntoa( *(IN_ADDR*)&nAddress ) ),
						nPort, (LPCTSTR)CSHA::HashToString( &m_pSHA1, TRUE ) );
				}
			}
		}
		
		if ( AddSourceURL( strURL, bURN, bSeen ? &tSeen : NULL ) ) nCount++;
	}
	
	return nCount;
}
Beispiel #30
0
int DBInterface::InsertRawSupply(vector<QueryHit>& query_hits)
{
//	file_name.Replace("\\","\\\\");
//	file_name.Replace("'", "\\'");

	//truncate the project name if its length is greater than 50
	CString project = query_hits[0].m_project;
	if(project.GetLength() > 50)
	{
		project.Truncate(50);
	}

	CString table = "SUPPLY_TABLE_";
	table += project;

	table.Replace('\\','_');			// replace the backslash with _
	table.Replace('\'', '_');		// replace the single quote "'" with _
	table.Replace(' ', '_');
	table.Replace('-', '_');
	table.Replace('&', '_');
	table.Replace('!', '_');
	table.Replace('$', '_');
	table.Replace('@', '_');
	table.Replace('%', '_');
	table.Replace('(', '_');
	table.Replace(')', '_');
	table.Replace('+', '_');
	table.Replace('~', '_');
	table.Replace('*', '_');
	table.Replace('.', '_');
	table.Replace(',', '_');
	table.Replace('?', '_');
	table.Replace(':', '_');
	table.Replace(';', '_');
	table.Replace('"', '_');
	table.Replace('/', '_');
	table.Replace('#', '_');

	
	int ret;
	char temp[32];
	memset(temp, 0, sizeof(temp));
	CString query = "INSERT INTO ";
	query += table;
	query += " (filename,filesize,hash,ip,port,search_id,timestamp,track,bitrate,frequency,duration) VALUES ";

	for(UINT i=0; i<query_hits.size(); i++)
	{
		query += "('";
		CString filename = query_hits[i].m_filename;
		filename.Replace("\\", "\\\\");
		filename.Replace("'", "\\'");
		query+= filename;
		query += "',";
		query += ultoa(query_hits[i].m_file_size, temp, 10);
		query += ",'";
		
		char hash[41];
		memset(&hash,0,sizeof(hash));
		for (int j = 0; j < 16; j++)
		{
			sprintf((char *)&hash[j*2],"%02x",((int)query_hits[i].m_hash[j])&0xFF);
		}
		query += hash;
		query += "',";
		query += itoa(query_hits[i].m_ip,temp,10);
		query += ",";
		query += itoa(query_hits[i].m_port,temp,10);
		query += ",";
		query += itoa(query_hits[i].m_search_id,temp,10);
		query += ",'";
		CString timestamp = query_hits[i].m_timestamp.Format("%Y%m%d%H%M%S");
		query += timestamp;
		query += "',";
		query += itoa(query_hits[i].m_track,temp,10);
		query += ",";
		query += itoa(query_hits[i].m_bitrate,temp,10);
		query += ",";
		query += itoa(query_hits[i].m_sample_frequency,temp,10);
		query += ",";
		query += itoa(query_hits[i].m_duration,temp,10);
		query += ")";
		if(i != query_hits.size()-1)
			query += ",";
	}

	ret = mysql_query(p_supply_conn,query);

	if(mysql_error(p_supply_conn)[0] != '\0')
	{
		CStdioFile file;
		if( file.Open("SQL_Error_Log.txt", CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite, NULL) != 0)
		{
			file.SeekToEnd();

			CString log;
			log = CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S");
			log += " InsertRawSupply(...) ";
			log += query;
			log += "\n";
			log += "Error: ";
			log += mysql_error(p_supply_conn);
			log += "\n\n";

			file.WriteString(log);
			file.Close();
		}
		else
		{
			DWORD error = GetLastError();
			MessageBox(NULL, "File Open Error: SQL_Error_Log.txt", "File Open Error", MB_OK);
		}

		TRACE(mysql_error(p_supply_conn));
		TRACE("\n");
		TRACE(query);
		TRACE("\n");
	}

	return ret;
}