Exemple #1
0
//--------------------------------------------------------------------
//--------------------------------------------------------------------
void CBFFileHelper::splitPath(LPCTSTR fullPath, CString& drive, CString& dir, CString& fname, CString& ext)
{
    TCHAR tDrive[_MAX_DRIVE];
    TCHAR tDir[_MAX_DIR];
    TCHAR tFname[_MAX_FNAME];
    TCHAR tExt[_MAX_EXT];
    _tsplitpath_s(fullPath, tDrive, tDir, tFname, tExt);

    drive = tDrive;
    dir = tDir;
    fname = tFname;
    ext = tExt;
}
Exemple #2
0
void CUT_Str::tsplitpath(const TCHAR * path, TCHAR * drive, size_t driveSizeInTCHARacters, TCHAR * dir,
   size_t dirSizeInTCHARacters, TCHAR * fname, size_t nameSizeInTCHARacters, TCHAR * ext, size_t extSizeInBytes)
{
#if _MSC_VER >= 1400
	_tsplitpath_s(path, drive, driveSizeInTCHARacters, dir, dirSizeInTCHARacters, fname, nameSizeInTCHARacters, ext, extSizeInBytes);
#else
	UNREFERENCED_PARAMETER(driveSizeInTCHARacters);
	UNREFERENCED_PARAMETER(dirSizeInTCHARacters);
	UNREFERENCED_PARAMETER(nameSizeInTCHARacters);
	UNREFERENCED_PARAMETER(extSizeInBytes);
	_tsplitpath(path, drive, dir, fname, ext);
#endif
}
Exemple #3
0
void CBCGPBaseInfoWriter::ParseFileName(const CString& pathName, CString& fileName, CString& extName)
{
	fileName.Empty ();
	extName.Empty ();

#if _MSC_VER < 1400
	_tsplitpath (pathName, NULL, NULL, fileName.GetBuffer (_MAX_FNAME), extName.GetBuffer (_MAX_EXT));
#else
	_tsplitpath_s (pathName, NULL, 0, NULL, 0, fileName.GetBuffer (_MAX_FNAME), _MAX_FNAME, extName.GetBuffer (_MAX_EXT), _MAX_EXT);
#endif

	fileName.ReleaseBuffer ();
	extName.ReleaseBuffer ();
}
void CDuiFrameWnd::AddFiles( const std::vector<PlayFileInfo> &vctString, bool bInit )
{
    COptionUI *pOptionTmp;
	CVerticalLayoutUI* pLayout = NULL;
    CDuiString  strTmp;
    TCHAR       szName[_MAX_FNAME];
    TCHAR       szExt[_MAX_EXT];
    unsigned    i, uWantedCount;

    pLayout = static_cast<CVerticalLayoutUI*>(m_PaintManager.FindControl(_T("playlist")));
    if (! pLayout)
    {
        return;
    }

    for(i = 0, uWantedCount = 0; i < vctString.size(); i++)
    {
        if (IsWantedFile(vctString[i].szFileName))
        {
            _tsplitpath_s(vctString[i].szFileName, NULL, 0, NULL, 0, szName, _MAX_FNAME, szExt, _MAX_EXT);
            strTmp.Format(_T("%s%s"), szName, szExt);   // 文件名

            pOptionTmp = new COptionUI;
            pOptionTmp->SetTextColor(0xFFC8C6CB);
            pOptionTmp->SetHotTextColor(0xFFC8C6CB);
            pOptionTmp->SetSelectedTextColor(0xFFC8C6CB);
            pOptionTmp->SetTag(U_TAG_PLAYLIST);
            pOptionTmp->SetText(strTmp);  
            pOptionTmp->SetAttribute(_T("height"), _T("22"));
            pOptionTmp->SetAttribute(_T("inset"), _T("7,0,0,0"));
            pOptionTmp->SetAttribute(_T("align"), _T("center"));
			pOptionTmp->SetAttribute(_T("font"),_T("4"));
			pOptionTmp->SetUserData(vctString[i].szFileName);
			pOptionTmp->SetName(vctString[i].szFileName);
			pOptionTmp->SetSelectedImage(_T("file='btn_bk.png'"));
            pLayout->Add(pOptionTmp);
            uWantedCount++;

            if (! bInit)
            {
                m_cPlayList.Add(vctString[i]);          // 完整路径
            }
        }        
    }

    Rand(m_queRand, uWantedCount);
    ShowPlaylist(true);
}
Exemple #5
0
CString GetProcessName()
{
	TCHAR szFilename[MAX_PATH] = {0};
	TCHAR szDriver[MAX_PATH] = {0};
	TCHAR szDir[MAX_PATH] = {0};
	TCHAR szFile[MAX_PATH] = {0};
	TCHAR szExt[MAX_PATH] = {0};

	DWORD dwLen = GetModuleFileName(NULL,szFilename,MAX_PATH);

	_tsplitpath_s(szFilename,szDriver,szDir,szFile,szExt);
	//_tcscat_s(szFile);

	return szFile;
	//return ((_tcsicmp(szFile,_T("communicator.exe")) == 0) || (_tcsicmp(szFile,_T("msnmsgr.exe")) == 0));
}
Exemple #6
0
bool initialize(bool i_isYamy)
{
#ifndef NDEBUG
    _TCHAR path[GANA_MAX_PATH];
    GetModuleFileName(NULL, path, GANA_MAX_PATH);
    _tsplitpath_s(path, NULL, 0, NULL, 0, g.m_moduleName, GANA_MAX_PATH, NULL, 0);
    if (_tcsnicmp(g.m_moduleName, _T("Dbgview"), sizeof(_T("Dbgview"))/sizeof(_TCHAR)) != 0 &&
            _tcsnicmp(g.m_moduleName, _T("windbg"), sizeof(_T("windbg"))/sizeof(_TCHAR)) != 0) {
        g.m_isLogging = true;
    }
#endif // !NDEBUG
#ifdef HOOK_LOG_TO_FILE
    _TCHAR logFileName[GANA_MAX_PATH];
    GetEnvironmentVariable(_T("USERPROFILE"), logFileName, NUMBER_OF(logFileName));
    _tcsncat(logFileName, _T("\\AppData\\LocalLow\\yamydll.txt"), _tcslen(_T("\\AppData\\LocalLow\\yamydll.log")));
    g.m_logFile = CreateFile(logFileName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                             OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
#endif // HOOK_LOG_TO_FILE
    WriteToLog("try to open mailslot\r\n");
    g.m_hMailslot =
        CreateFile(NOTIFY_MAILSLOT_NAME, GENERIC_WRITE,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   (SECURITY_ATTRIBUTES *)NULL, OPEN_EXISTING,
                   FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);
    if (g.m_hMailslot == INVALID_HANDLE_VALUE) {
        HOOK_RPT2("MAYU: %S create mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError());
        WriteToLog("open mailslot NG\r\n");
    } else {
        HOOK_RPT1("MAYU: %S create mailslot successed\r\n", g.m_moduleName);
        WriteToLog("open mailslot OK\r\n");
    }
    if (!mapHookData(i_isYamy))
        return false;
    _tsetlocale(LC_ALL, _T(""));
    g.m_WM_MAYU_MESSAGE =
        RegisterWindowMessage(addSessionId(WM_MAYU_MESSAGE_NAME).c_str());
    g.m_hwndTaskTray = g_hookData->m_hwndTaskTray;
    if (!i_isYamy) {
        NotifyThreadAttach ntd;
        ntd.m_type = Notify::Type_threadAttach;
        ntd.m_threadId = GetCurrentThreadId();
        notify(&ntd, sizeof(ntd));
    }
    g.m_isInitialized = true;
    return true;
}
Exemple #7
0
CString GetFileNameComp(LPCTSTR fileName, WORD type)
{
   // Get file name component
   CString compStr = EMPTY_STR;
   TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], name[_MAX_FNAME], ext[_MAX_EXT];
   _tsplitpath_s(fileName[0] == _T('"') ? &fileName[1] : fileName, drive, _MAX_DRIVE, dir, _MAX_DIR, name, _MAX_FNAME, ext, _MAX_EXT);
   if (type & eFcDrive)
      compStr += drive;
   if (type & eFcDir)
      compStr += dir;
   if (type & eFcName)
      compStr += name;
   if (type & eFcType)
     compStr += ext;
   compStr.Remove(_T('"'));
   return compStr;
}
Exemple #8
0
CMGTOOls::CMGTOOls(void)
{
	//absolute Config.
	{
		TCHAR strModuleFileName[MAX_PATH];
		TCHAR strPath[MAX_PATH];
		GetModuleFileName(NULL,strModuleFileName,MAX_PATH);
		_tsplitpath_s(strModuleFileName, m_strModulePath,_countof(m_strModulePath), strPath,_countof(strPath),NULL,0,NULL,0);
		_tcscat_s(m_strModulePath,_countof(m_strModulePath),strPath);  
		_tcscpy(m_strMgConfigFile_Absolute_Path,m_strModulePath); 
		_tcscat_s(m_strMgConfigFile_Absolute_Path,_countof(m_strMgConfigFile_Absolute_Path),_T("MgCaptureCfg.ini"));
		
	}
	//relative Config .
   m_nChannelID = 0;
   m_bRelative = 0;
}
Exemple #9
0
	/**
	 * @brief 例外発生場所を文字列にして返す
	 *
	 */
	acut::TString Exception::what() const
	{
		// __FILE__ はフルパスなので、ファイル名のみ取り出す
		TCHAR drive[MAX_PATH];
		TCHAR directory[MAX_PATH];
		TCHAR fileName[MAX_PATH];
		TCHAR extension[MAX_PATH];
		_tsplitpath_s(m_file.c_str(), drive, directory, fileName, extension);

		acut::tstringstream ss;
		ss << _T("FILE = ") << fileName << extension
			<< _T(", LINE = ") << m_line
			<< _T(", FUNCTION = ") << m_function
			<< std::endl;

		return ss.str();
	}
Exemple #10
0
CString GetDirNoSlash(const CString& strFSpec)
{
	if( strFSpec.IsEmpty() )
		return strFSpec;

	TCHAR	drive[_MAX_DRIVE];
	TCHAR	dir[_MAX_DIR];
	TCHAR	name[_MAX_FNAME];
	TCHAR	ext[_MAX_EXT];
	_tsplitpath_s( (LPCTSTR)strFSpec, drive, dir, name, ext );

	CString strDir = drive;
	strDir += dir;

	if( strDir.Right(1) == _T("\\") )
		strDir = strDir.Left(strDir.GetLength() - 1);
	return strDir;
}
Exemple #11
0
	Server::Server(void) : m_pSessions(), m_hStopEvent(0), 
		m_hIoPort(0), m_hListener(0), IsInConsole(false), ServiceBase(APP_NAME)
	{
		m_pSessions.reserve(MAX_SESSIONS);

		// getting current execution directory path.
		_TCHAR szFileName[_MAX_PATH];
		GetModuleFileName(NULL, szFileName, sizeof(szFileName) / sizeof(_TCHAR));

		_TCHAR szDrive[_MAX_DRIVE],
			szPath[_MAX_PATH],
			szFilename[_MAX_FNAME],
			szExtension[_MAX_EXT];

		_tsplitpath_s(szFileName, szDrive, szPath, szFilename, szExtension);
		m_pPath = szDrive;
		m_pPath += szPath;
	}
Exemple #12
0
CString CStkDatabase::GetAppPath()
{
	if (!m_strPath.IsEmpty())
		return m_strPath;

	TCHAR szFilePath[_MAX_PATH];
	TCHAR szDrive[_MAX_DRIVE];
	TCHAR szDir[_MAX_DIR];
	TCHAR szFileName[_MAX_FNAME];
	TCHAR szExt[_MAX_EXT];

	if (GetModuleFileName(NULL, szFilePath, _MAX_PATH) == NULL)
		return _T("");

	_tsplitpath_s(szFilePath, szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFileName, _MAX_FNAME, szExt, _MAX_EXT);
	m_strPath = szDrive;
	m_strPath += szDir;

	return m_strPath;
}
bool FindFileExt(LPCTSTR pstrPath, LPCTSTR pstrExtFilter)
{
    if (! pstrPath || ! pstrExtFilter)
    {
        return false;
    }

    TCHAR szExt[_MAX_EXT] = _T("");

    _tsplitpath_s(pstrPath, NULL, 0, NULL, 0, NULL, 0, szExt, _MAX_EXT);
    _tcslwr_s(szExt, _MAX_EXT);

    if(_tcslen(szExt))  
    {
        _tcscat_s(szExt, _MAX_EXT, _T(";"));    // .mo不符合条件,由于会匹配到.mov,所以在后面加上【;】来判断是否完全匹配
        return NULL != _tcsstr(pstrExtFilter, szExt);
    }

    return false;
}
Exemple #14
0
INT GSpriteMgr::Add(ID3D11Device*	 pDevice, 
	TCHAR *pTextureFileName,
	TCHAR *pShaderFileName, 
	ID3D11BlendState* pBlendState,
	bool bInstancing)
{
	TCHAR szFileName[MAX_PATH];
	TCHAR Drive[MAX_PATH];
	TCHAR Dir[MAX_PATH];
	TCHAR FName[MAX_PATH];
	TCHAR Ext[MAX_PATH];
	if (pTextureFileName)
	{
		_tsplitpath_s(pTextureFileName, Drive, Dir, FName, Ext);
		Ext[4] = 0;
		memset(szFileName, 0, sizeof(TCHAR) * MAX_PATH);
		_stprintf_s(szFileName, _T("%s%s"), FName, Ext);

		for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++)
		{
			GSprite *pPoint = (GSprite *)(*itor).second;
			if (!_tcsicmp(pPoint->m_szName.c_str(), szFileName))
			{
				return (*itor).first;
			}
		}
	}
	GSprite *pPoint = NULL;
	SAFE_NEW(pPoint, GSprite);
	assert(pPoint);
	pPoint->m_szPath = Dir;

	if (FAILED(pPoint->Load(pDevice, pShaderFileName, pTextureFileName, bInstancing, pBlendState)))
	{
		SAFE_DEL(pPoint);
		return 0;
	}
	TMap.insert(make_pair(++m_iCurIndex, pPoint));
	pPoint->m_iIndex = m_iCurIndex;
	return m_iCurIndex;
}
Exemple #15
0
int _tmain(int argc, _TCHAR* argv[])
{
	ExecutionArguments arguments;
	arguments.RunInteractively = false;

	//First find our executable's directory. We will find Stub.js and
	//js.exe there
	{
		TCHAR drive[MAX_PATH];
		TCHAR directory[MAX_PATH];
		_tsplitpath_s(argv[0], drive, MAX_PATH, directory, MAX_PATH, nullptr, 0, nullptr, 0);

		_tcscpy_s(arguments.BasePath, drive);
		_tcscpy_s(arguments.BasePath + _tcslen(arguments.BasePath),
			MAX_PATH - _tcslen(arguments.BasePath), directory);
	}
	
	for (int i = 1; i < argc; ++i)
	{
		if (_tcscmp(_T("-f"), argv[i]) == 0 && i + 1 < argc)
		{
			arguments.FilesToExecute.push_back(argv[++i]);
		}
		else if (_tcscmp(_T("-i"), argv[i]) == 0)
		{
			arguments.RunInteractively = true;
		}
		else
		{
			arguments.ShellArguments.push_back(argv[i]);
		}
	}

	//One fix up: if we have no files to execute, we should run interactively.
	if (arguments.FilesToExecute.empty() && !arguments.RunInteractively)
		arguments.RunInteractively = true;

	StartJavaScriptShell(arguments);
}
Exemple #16
0
  // In following, drive will be empty on non-Windows platforms
bool pws_os::splitpath(const stringT &path,
                       stringT &drive, stringT &dir,
                       stringT &file, stringT &ext)
{
  TCHAR tdrv[_MAX_DRIVE];
  TCHAR tdir[_MAX_DIR];
  TCHAR tname[_MAX_FNAME];
  TCHAR text[_MAX_EXT];

  wmemset(tdrv, 0, sizeof(tdrv) / sizeof(TCHAR));
  wmemset(tdir, 0, sizeof(tdir) / sizeof(TCHAR));
  wmemset(tname, 0, sizeof(tname) / sizeof(TCHAR));
  wmemset(text, 0, sizeof(text) / sizeof(TCHAR));

  if (_tsplitpath_s(path.c_str(), tdrv, tdir, tname, text) == 0) {
    drive = tdrv;
    dir = tdir;
    file = tname;
    ext = text;
    return true;
  } else
    return false;
}
Exemple #17
0
bool			KBitmap::Load(TCHAR* pFileName)
{
	m_hScreenDC = g_hScreenDC;
	m_hOffScreenDC = g_hOffScreenDC;
	m_hBitmap = (HBITMAP)LoadImage(g_hInstance,
		pFileName, IMAGE_BITMAP, 0, 0,
		LR_DEFAULTSIZE | LR_LOADFROMFILE);
	GetObject(m_hBitmap, sizeof(BITMAP), &m_hBitInfo);
	// 메모리 DC 할당( 화면 DC와 호환가능한 제 2의 DC 생성)
	m_hMemDC = CreateCompatibleDC(m_hScreenDC);
	// 메모리 DC에 비트맵을 적용
	m_hOldBitmap = (HBITMAP)SelectObject(m_hMemDC, m_hBitmap);

	TCHAR Drive[MAX_PATH] = { 0, };
	TCHAR Dir[MAX_PATH] = { 0, };
	TCHAR Name[MAX_PATH] = { 0, };
	TCHAR Ext[MAX_PATH] = { 0, };
	TCHAR SaveName[MAX_PATH] = { 0, };
	_tsplitpath_s(pFileName, Drive, Dir, Name, Ext);
	_stprintf_s(SaveName, _T("%s%s"), Name, Ext);
	_tcscpy_s(m_szName, SaveName);
	return true;
}
Exemple #18
0
        void 
    #else
        Int16u 
    #endif //(_MSC_VER)
               FNSplit (const char * pathP, 
                        char       * driveP,
						size_t       driveSz,
                        char       * dirP, 
						size_t       dirSz,
                        char       * nameP,
						size_t       nameSz,
                        char       * extP,
						size_t       extSz)
    {
    #if defined (_MSC_VER)
        _tsplitpath_s(pathP, driveP, driveSz, dirP, dirSz, nameP, nameSz, extP, nameSz);
    #elif defined(PLAT_WINDU)
        _tsplitpath (pathP, driveP, dirP, nameP, extP);
        Int16u result = TRUE;
    #else 
        Int16u result = (Int16u)fnsplit (pathP, driveP, dirP, nameP, extP);
    #endif //(_MSC_VER)

        if (dirP != 0)
        {
            Int16u dirL = lstrlen (dirP);
            if (dirL > 0 && dirP [dirL - 1] != '/' && dirP [dirL - 1] != '\\')
            {
                dirP [dirL] = '\\';
                dirP [dirL + 1] = '\0';
            }
        }

    #if !defined (_MSC_VER)
        return result;
    #endif //!defined (_MSC_VER)
    }
LPCTSTR CSnapshotManager::getBaseDir() const
{
	static tstring sinstallDir = _T("");

	if (sinstallDir.size() > 0) return sinstallDir.c_str();

	TCHAR InstallDir[MAX_PATH];
	TCHAR ExeName[MAX_PATH], DirName[MAX_PATH], Drive[3];

	::GetModuleFileName(NULL, ExeName, MAX_PATH);
	_tsplitpath_s(ExeName, Drive, 3, DirName, MAX_PATH, NULL, 0, NULL, 0);
	int Count =_sntprintf_s(InstallDir, MAX_PATH, _TRUNCATE, TEXT("%s%s"), Drive, DirName);
	for(Count -= 1; Count >= 0; Count--)
	{
		if (InstallDir[Count] == TEXT('\\'))
		{
			InstallDir[Count+1] = TEXT('\0');
			break;
		}
	}

	sinstallDir = InstallDir;
	return sinstallDir.c_str();
}
Exemple #20
0
BOOL CBatManager::CreateBatFile(BAT_WORK_INFO* info, wstring batSrcFilePath, wstring& batFilePath )
{
	if( info == NULL ){
		return FALSE;
	}
	GetModuleFolderPath(batFilePath);
	batFilePath+=L"\\EpgTimer_Bon_RecEnd.bat";

	//バッチの作成
	HANDLE hRead = CreateFileW( batSrcFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hRead == INVALID_HANDLE_VALUE ){
		return FALSE;
	}
	HANDLE hWrite = _CreateFile2( batFilePath.c_str(), GENERIC_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hWrite == INVALID_HANDLE_VALUE ){
		CloseHandle(hRead);
		return FALSE;
	}

	DWORD dwRead=0;
	DWORD dwL = GetFileSize(hRead, NULL);
	char* pBuff = new char[dwL+1];
	ZeroMemory(pBuff, dwL+1);
	ReadFile(hRead, pBuff, dwL, &dwRead, NULL );
	CloseHandle(hRead);

	string strRead = "";
	strRead = pBuff;
	SAFE_DELETE_ARRAY(pBuff);

	string strRecFilePath="";
	string strFolderPath="";
	string strFileName="";
	string strTitle="";
	string strSDYYYY="";
	string strSDYY="";
	string strSDMM="";
	string strSDM="";
	string strSDDD="";
	string strSDD="";
	string strSDW="";
	string strSTHH="";
	string strSTH="";
	string strSTMM="";
	string strSTM="";
	string strSTSS="";
	string strSTS="";
	string strEDYYYY="";
	string strEDYY="";
	string strEDMM="";
	string strEDM="";
	string strEDDD="";
	string strEDD="";
	string strEDW="";
	string strETHH="";
	string strETH="";
	string strETMM="";
	string strETM="";
	string strETSS="";
	string strETS="";
	string strONID10="";
	string strTSID10="";
	string strSID10="";
	string strEID10="";
	string strONID16="";
	string strTSID16="";
	string strSID16="";
	string strEID16="";
	string strServiceName="";
	string strSDYYYY28="";
	string strSDYY28="";
	string strSDMM28="";
	string strSDM28="";
	string strSDDD28="";
	string strSDD28="";
	string strSDW28="";
	string strSTHH28="";
	string strSTH28="";
	string strEDYYYY28="";
	string strEDYY28="";
	string strEDMM28="";
	string strEDM28="";
	string strEDDD28="";
	string strEDD28="";
	string strEDW28="";
	string strETHH28="";
	string strETH28="";
	string strDUH="";
	string strDUHH="";
	string strDUM="";
	string strDUMM="";
	string strDUS="";
	string strDUSS="";
	string strTitle2="";
	string strDrops="";
	string strScrambles="";
	string strResult="";
	string strTitleF="";
	string strTitle2F="";
	string strAddKey="";

	WtoA(info->recFileInfo.recFilePath, strRecFilePath);

	WCHAR szDrive[_MAX_DRIVE];
	WCHAR szDir[_MAX_DIR];
	WCHAR szFname[_MAX_FNAME];
	WCHAR szExt[_MAX_EXT];
	WCHAR szPath[_MAX_PATH] = L"";
	_tsplitpath_s( info->recFileInfo.recFilePath.c_str(), szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFname, _MAX_FNAME, szExt, _MAX_EXT );
	_tmakepath_s( szPath, _MAX_PATH, szDrive, szDir, NULL, NULL );
	wstring strFolder;
	strFolder = szPath;
	ChkFolderPath(strFolder);

	WtoA(szFname, strFileName);
	WtoA(strFolder, strFolderPath);
	WtoA(info->recFileInfo.title, strTitle);

	Format(strSDYYYY, "%04d", info->recFileInfo.startTime.wYear);
	Format(strSDYY, "%02d", info->recFileInfo.startTime.wYear%100);
	Format(strSDMM, "%02d", info->recFileInfo.startTime.wMonth);
	Format(strSDM, "%d", info->recFileInfo.startTime.wMonth);
	Format(strSDDD, "%02d", info->recFileInfo.startTime.wDay);
	Format(strSDD, "%d", info->recFileInfo.startTime.wDay);
	GetDayOfWeekString2(info->recFileInfo.startTime, strSDW);
	Format(strSTHH, "%02d", info->recFileInfo.startTime.wHour);
	Format(strSTH, "%d", info->recFileInfo.startTime.wHour);
	Format(strSTMM, "%02d", info->recFileInfo.startTime.wMinute);
	Format(strSTM, "%d", info->recFileInfo.startTime.wMinute);
	Format(strSTSS, "%02d", info->recFileInfo.startTime.wSecond);
	Format(strSTS, "%d", info->recFileInfo.startTime.wSecond);

	SYSTEMTIME t28TimeS;
	if( 0 <= info->recFileInfo.startTime.wHour && info->recFileInfo.startTime.wHour < 4 ){
		GetSumTime(info->recFileInfo.startTime, -24*60*60, &t28TimeS);
		GetDayOfWeekString2(t28TimeS, strSDW28);
		t28TimeS.wHour+=24;
	}else{
		t28TimeS = info->recFileInfo.startTime;
		GetDayOfWeekString2(t28TimeS, strSDW28);
	}

	Format(strSDYYYY28, "%04d", t28TimeS.wYear);
	Format(strSDYY28, "%02d", t28TimeS.wYear%100);
	Format(strSDMM28, "%02d", t28TimeS.wMonth);
	Format(strSDM28, "%d", t28TimeS.wMonth);
	Format(strSDDD28, "%02d", t28TimeS.wDay);
	Format(strSDD28, "%d", t28TimeS.wDay);
	Format(strSTHH28, "%02d", t28TimeS.wHour);
	Format(strSTH28, "%d", t28TimeS.wHour);

	SYSTEMTIME tEnd;
	GetI64Time(info->recFileInfo.startTime, info->recFileInfo.durationSecond, NULL, NULL, &tEnd);

	Format(strEDYYYY, "%04d", tEnd.wYear);
	Format(strEDYY, "%02d", tEnd.wYear%100);
	Format(strEDMM, "%02d", tEnd.wMonth);
	Format(strEDM, "%d", tEnd.wMonth);
	Format(strEDDD, "%02d", tEnd.wDay);
	Format(strEDD, "%d", tEnd.wDay);
	GetDayOfWeekString2(tEnd, strEDW);
	Format(strETHH, "%02d", tEnd.wHour);
	Format(strETH, "%d", tEnd.wHour);
	Format(strETMM, "%02d", tEnd.wMinute);
	Format(strETM, "%d", tEnd.wMinute);
	Format(strETSS, "%02d", tEnd.wSecond);
	Format(strETS, "%d", tEnd.wSecond);

	SYSTEMTIME t28TimeE;
	if( 0 <= tEnd.wHour && tEnd.wHour < 4 ){
		GetSumTime(tEnd, -24*60*60, &t28TimeE);
		GetDayOfWeekString2(t28TimeE, strEDW28);
		t28TimeE.wHour+=24;
	}else{
		t28TimeE = tEnd;
		GetDayOfWeekString2(tEnd, strEDW28);
	}

	Format(strEDYYYY28, "%04d", t28TimeE.wYear);
	Format(strEDYY28, "%02d", t28TimeE.wYear%100);
	Format(strEDMM28, "%02d", t28TimeE.wMonth);
	Format(strEDM28, "%d", t28TimeE.wMonth);
	Format(strEDDD28, "%02d", t28TimeE.wDay);
	Format(strEDD28, "%d", t28TimeE.wDay);
	Format(strETHH28, "%02d", t28TimeE.wHour);
	Format(strETH28, "%d", t28TimeE.wHour);

	Format(strONID10, "%d", info->recFileInfo.originalNetworkID);
	Format(strTSID10, "%d", info->recFileInfo.transportStreamID);
	Format(strSID10, "%d", info->recFileInfo.serviceID);
	Format(strEID10, "%d", info->recFileInfo.eventID);
	Format(strONID16, "%04X", info->recFileInfo.originalNetworkID);
	Format(strTSID16, "%04X", info->recFileInfo.transportStreamID);
	Format(strSID16, "%04X", info->recFileInfo.serviceID);
	Format(strEID16, "%04X", info->recFileInfo.eventID);

	WtoA(info->recFileInfo.serviceName, strServiceName);

	Format(strDUHH, "%02d", info->recFileInfo.durationSecond/(60*60));
	Format(strDUH, "%d", info->recFileInfo.durationSecond/(60*60));
	Format(strDUMM, "%02d", (info->recFileInfo.durationSecond%(60*60))/60);
	Format(strDUM, "%d", (info->recFileInfo.durationSecond%(60*60))/60);
	Format(strDUSS, "%02d", info->recFileInfo.durationSecond%60);
	Format(strDUS, "%d", info->recFileInfo.durationSecond%60);

	wstring strTemp = info->recFileInfo.title;
	while( (strTemp.find(L"[") != string::npos) && (strTemp.find(L"]") != string::npos) ){
		wstring strSep1=L"";
		wstring strSep2=L"";
		Separate(strTemp, L"[", strSep1, strTemp);
		Separate(strTemp, L"]", strSep2, strTemp);
		strSep1 += strTemp;
		strTemp = strSep1;
	}
	WtoA(strTemp, strTitle2);

	Format(strDrops, "%I64d", info->recFileInfo.drops);
	Format(strScrambles, "%I64d", info->recFileInfo.scrambles);
	WtoA(info->recFileInfo.comment, strResult);

	CheckFileName(strTitleF);
	CheckFileName(strTemp);
	WtoA(strTemp, strTitle2F);
	strTemp = info->recFileInfo.title;
	CheckFileName(strTemp);
	WtoA(strTemp, strTitleF);

	if( info->reserveInfo.comment.find(L"EPG自動予約(") != string::npos ){
		WtoA(info->reserveInfo.comment, strAddKey);
		Replace(strAddKey, "EPG自動予約(", "");
		strAddKey.erase(strAddKey.length()-1, 1);
	}

	Replace(strRead, "$FilePath$", strRecFilePath);
	Replace(strRead, "$FolderPath$", strFolderPath);
	Replace(strRead, "$FileName$", strFileName);
	Replace(strRead, "$Title$", strTitle);
	Replace(strRead, "$SDYYYY$", strSDYYYY);
	Replace(strRead, "$SDYY$", strSDYY);
	Replace(strRead, "$SDMM$", strSDMM);
	Replace(strRead, "$SDM$", strSDM);
	Replace(strRead, "$SDDD$", strSDDD);
	Replace(strRead, "$SDD$", strSDD);
	Replace(strRead, "$SDW$", strSDW);
	Replace(strRead, "$STHH$", strSTHH);
	Replace(strRead, "$STH$", strSTH);
	Replace(strRead, "$STMM$", strSTMM);
	Replace(strRead, "$STM$", strSTM);
	Replace(strRead, "$STSS$", strSTSS);
	Replace(strRead, "$STS$", strSTS);
	Replace(strRead, "$EDYYYY$", strEDYYYY);
	Replace(strRead, "$EDYY$", strEDYY);
	Replace(strRead, "$EDMM$", strEDMM);
	Replace(strRead, "$EDM$", strEDM);
	Replace(strRead, "$EDDD$", strEDDD);
	Replace(strRead, "$EDD$", strEDD);
	Replace(strRead, "$EDW$", strEDW);
	Replace(strRead, "$ETHH$", strETHH);
	Replace(strRead, "$ETH$", strETH);
	Replace(strRead, "$ETMM$", strETMM);
	Replace(strRead, "$ETM$", strETM);
	Replace(strRead, "$ETSS$", strETSS);
	Replace(strRead, "$ETS$", strETS);
	Replace(strRead, "$ONID10$", strONID10);
	Replace(strRead, "$TSID10$", strTSID10);
	Replace(strRead, "$SID10$", strSID10);
	Replace(strRead, "$EID10$", strEID10);
	Replace(strRead, "$ONID16$", strONID16);
	Replace(strRead, "$TSID16$", strTSID16);
	Replace(strRead, "$SID16$", strSID16);
	Replace(strRead, "$EID16$", strEID16);
	Replace(strRead, "$ServiceName$", strServiceName);
	Replace(strRead, "$SDYYYY28$", strSDYYYY28);
	Replace(strRead, "$SDYY28$", strSDYY28);
	Replace(strRead, "$SDMM28$", strSDMM28);
	Replace(strRead, "$SDM28$", strSDM28);
	Replace(strRead, "$SDDD28$", strSDDD28);
	Replace(strRead, "$SDD28$", strSDD28);
	Replace(strRead, "$SDW28$", strSDW28);
	Replace(strRead, "$STHH28$", strSTHH28);
	Replace(strRead, "$STH28$", strSTH28);
	Replace(strRead, "$EDYYYY28$", strEDYYYY28);
	Replace(strRead, "$EDYY28$", strEDYY28);
	Replace(strRead, "$EDMM28$", strEDMM28);
	Replace(strRead, "$EDM28$", strEDM28);
	Replace(strRead, "$EDDD28$", strEDDD28);
	Replace(strRead, "$EDD28$", strEDD28);
	Replace(strRead, "$EDW28$", strEDW28);
	Replace(strRead, "$ETHH28$", strETHH28);
	Replace(strRead, "$ETH28$", strETH28);
	Replace(strRead, "$DUHH$", strDUHH);
	Replace(strRead, "$DUH$", strDUH);
	Replace(strRead, "$DUMM$", strDUMM);
	Replace(strRead, "$DUM$", strDUM);
	Replace(strRead, "$DUSS$", strDUSS);
	Replace(strRead, "$DUS$", strDUS);
	Replace(strRead, "$Title2$", strTitle2);
	Replace(strRead, "$Drops$", strDrops);
	Replace(strRead, "$Scrambles$", strScrambles);
	Replace(strRead, "$Result$", strResult);
	Replace(strRead, "$TitleF$", strTitleF);
	Replace(strRead, "$Title2F$", strTitle2F);
	Replace(strRead, "$AddKey$", strAddKey);

	DWORD dwWrite=0;
	WriteFile(hWrite, strRead.c_str(), (DWORD)strRead.length(), &dwWrite, NULL );
	CloseHandle(hWrite);

	return TRUE;
}
Exemple #21
0
MBASEAPI CString MIRACLEEXPORT mirGetFileTitleNoExt(LPCTSTR lpszPath)
{	
	TCHAR szFname[FILE_PATH_MAX];
	_tsplitpath_s(lpszPath, NULL,0, NULL,0, szFname,4096, NULL,0);
	return  CString(szFname);
}
Exemple #22
0
static void watch_directory(folder_watcher* pfw)
{
	DWORD dwWaitStatus;
	HANDLE dwChangeHandles[2];
	TCHAR lpDrive[4];
	TCHAR lpFile[_MAX_FNAME];
	TCHAR lpExt[_MAX_EXT];

	_tsplitpath_s(LPTSTR(pfw->get_directory().data()), lpDrive, 4, NULL, 0, lpFile, _MAX_FNAME, lpExt, _MAX_EXT);

	lpDrive[2] = (TCHAR)'\\';
	lpDrive[3] = (TCHAR)'\0';

	// Watch the directory for file creation and deletion. 

	dwChangeHandles[0] = FindFirstChangeNotification(
		LPTSTR(pfw->get_directory().data()), // directory to watch 
		TRUE,                         // do not watch subtree 
		pfw->get_filter()); // watch file name changes 

	if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
	{
		printf("\n ERROR: FindFirstChangeNotification function failed.\n");
		ExitProcess(GetLastError());
	}

	// Watch the subtree for directory creation and deletion. 
	
	dwChangeHandles[1] = FindFirstChangeNotification(
		lpDrive,                       // directory to watch 
		TRUE,                          // watch the subtree 
		FILE_NOTIFY_CHANGE_DIR_NAME);  // watch dir name changes 

	if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
	{
		printf("\n ERROR: FindFirstChangeNotification function failed.\n");
		ExitProcess(GetLastError());
	}


	// Make a final validation check on our handles.

	if ((dwChangeHandles[0] == NULL) || (dwChangeHandles[1] == NULL))
	{
		printf("\n ERROR: Unexpected NULL from FindFirstChangeNotification.\n");
		ExitProcess(GetLastError());
	}

	// Change notification is set. Now wait on both notification 
	// handles and refresh accordingly. 

	while (true)
	{
		// Wait for notification.

		//printf("\nWaiting for notification...\n");

		dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE, WAIT_TIME);

		if (!pfw->is_running())
		{
			break;
		}

		switch (dwWaitStatus)
		{
		case WAIT_OBJECT_0:

			// A file was created, renamed, or deleted in the directory.
			// Refresh this directory and restart the notification.
			//printf("fileupdate\n");
			pfw->call_callback();
			if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)
			{
				printf("\n ERROR: FindNextChangeNotification function failed.\n");
				ExitProcess(GetLastError());
			}
			
			break;

		case WAIT_OBJECT_0 + 1:

			// A directory was created, renamed, or deleted.
			// Refresh the tree and restart the notification.
			//printf("folderupdate\n");
			pfw->call_callback();
			if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)
			{
				printf("\n ERROR: FindNextChangeNotification function failed.\n");
				ExitProcess(GetLastError());
			}
			break;

		case WAIT_TIMEOUT:

			// A timeout occurred, this would happen if some value other 
			// than INFINITE is used in the Wait call and no changes occur.
			// In a single-threaded environment you might not want an
			// INFINITE wait.

			//printf("\nNo changes in the timeout period.\n");
			break;

		default:
			printf("\n ERROR: Unhandled dwWaitStatus.\n");
			ExitProcess(GetLastError());
			break;
		}
	}
}
//*******************************************************************************
BOOL CBCGPTagManager::LoadFromFile (LPCTSTR lpszFileName)
{
	ASSERT_VALID (this);
	ASSERT (lpszFileName != NULL);

	SetBuffer (NULL);

	CString strFileName = lpszFileName;

	CString strBuffer;
	CString strPath = strFileName;

	if (strFileName.Find (TCHAR('\\')) == -1 &&
		strFileName.Find (TCHAR('/')) == -1 &&
		strFileName.Find (TCHAR(':')) == -1)
	{
		TCHAR lpszFilePath [_MAX_PATH];
		if (::GetModuleFileName (NULL, lpszFilePath, _MAX_PATH) > 0)
		{
			TCHAR path_buffer[_MAX_PATH];   
			TCHAR drive[_MAX_DRIVE];   
			TCHAR dir[_MAX_DIR];
			TCHAR fname[_MAX_FNAME];   
			TCHAR ext[_MAX_EXT];

#if _MSC_VER < 1400
			_tsplitpath (lpszFilePath, drive, dir, NULL, NULL);
			_tsplitpath (strFileName, NULL, NULL, fname, ext);

			_tmakepath (path_buffer, drive, dir, fname, ext);
#else
			_tsplitpath_s (lpszFilePath, drive, _MAX_DRIVE, dir, _MAX_DIR, NULL, 0, NULL, 0);
			_tsplitpath_s (strFileName, NULL, 0, NULL, 0, fname, _MAX_FNAME, ext, _MAX_EXT);

			_tmakepath_s (path_buffer, drive, dir, fname, ext);
#endif

			strPath = path_buffer;
		}
	}

	try
	{
		CStdioFile file;
		if (!file.Open (strPath, CFile::modeRead))
		{
			TRACE(_T("CBCGPTagManager::LoadFromFile: File not found: %s"), strFileName);
			return FALSE;
		}

		CString str;

		while (file.ReadString (str))
		{
			strBuffer += str;
		}
	}
	catch (CFileException* pEx)
	{
		pEx->ReportError ();
		pEx->Delete ();

		return FALSE;
	}

	SetBuffer (strBuffer);
	return TRUE;
}
FileChildWindow::FileChildWindow(HWND hwnd, const FileChildWndInfo& info)
 :	super(hwnd, info)
{
	CONTEXT("FileChildWindow::FileChildWindow()");

	TCHAR drv[_MAX_DRIVE+1];
	Entry* entry = NULL;

	_left = NULL;
	_right = NULL;

	switch(info._etype) {
#ifdef __WINE__
	  case ET_UNIX:
		_root._drive_type = GetDriveType(info._path);
		_root._sort_order = SORT_NAME;

		_tsplitpath(info._path, drv, NULL, NULL, NULL);
		lstrcat(drv, TEXT("/"));
		lstrcpy(_root._volname, TEXT("root fs"));
		_root._fs_flags = 0;
		lstrcpy(_root._fs, TEXT("unixfs"));
		lstrcpy(_root._path, TEXT("/"));
		_root._entry = new UnixDirectory(_root._path);
		entry = _root.read_tree(info._path+_tcslen(_root._path));
		break;
#endif

	  case ET_NTOBJS:
		_root._drive_type = DRIVE_UNKNOWN;
		_root._sort_order = SORT_NAME;

		_tsplitpath_s(info._path, drv, COUNTOF(drv), NULL, 0, NULL, 0, NULL, 0);
		lstrcat(drv, TEXT("\\"));
		lstrcpy(_root._volname, TEXT("NT Object Namespace"));
		lstrcpy(_root._fs, TEXT("NTOBJ"));
		lstrcpy(_root._path, drv);
		_root._entry = new NtObjDirectory(_root._path);
		entry = _root.read_tree(info._path+_tcslen(_root._path));
		break;

	  case ET_REGISTRY:
		_root._drive_type = DRIVE_UNKNOWN;
		_root._sort_order = SORT_NONE;

		_tsplitpath_s(info._path, drv, COUNTOF(drv), NULL, 0, NULL, 0, NULL, 0);
		lstrcat(drv, TEXT("\\"));
		lstrcpy(_root._volname, TEXT("Registry"));
		lstrcpy(_root._fs, TEXT("Registry"));
		lstrcpy(_root._path, drv);
		_root._entry = new RegistryRoot();
		entry = _root.read_tree(info._path+_tcslen(_root._path));
		break;

	  case ET_FAT: {
		_root._drive_type = DRIVE_UNKNOWN;
		_root._sort_order = SORT_NONE;

		_tsplitpath_s(info._path, drv, COUNTOF(drv), NULL, 0, NULL, 0, NULL, 0);
		lstrcat(drv, TEXT("\\"));
		lstrcpy(_root._volname, TEXT("FAT XXX"));	//@@
		lstrcpy(_root._fs, TEXT("FAT"));
		lstrcpy(_root._path, drv);
		FATDrive* drive = new FATDrive(TEXT("c:/odyssey-emu/c.img"));	//TEXT("\\\\.\\F:"));	//@@

		if (drive->_hDrive != INVALID_HANDLE_VALUE) {
			_root._entry = drive;
			entry = _root.read_tree(info._path+_tcslen(_root._path));
		}
		break;}

#ifndef _NO_WIN_FS
	  default:	// ET_WINDOWS
		_root._drive_type = GetDriveType(info._path);
		_root._sort_order = SORT_NAME;

		_tsplitpath_s(info._path, drv, COUNTOF(drv), NULL, 0, NULL, 0, NULL, 0);
		lstrcat(drv, TEXT("\\"));
		GetVolumeInformation(drv, _root._volname, _MAX_FNAME, 0, 0, &_root._fs_flags, _root._fs, COUNTOF(_root._fs));
		lstrcpy(_root._path, drv);
		_root._entry = new WinDirectory(_root._path);
		entry = _root.read_tree(info._path+_tcslen(_root._path));
		break;
#else
	default:
#endif

	  case ET_SHELL: {	//@@ separate FileChildWindow into ShellChildWindow, WinChildWindow, UnixChildWindow ?
		_root._drive_type = DRIVE_UNKNOWN;
		_root._sort_order = SORT_NAME;

		lstrcpy(drv, TEXT("\\"));
		lstrcpy(_root._volname, TEXT("Desktop"));
		_root._fs_flags = 0;
		lstrcpy(_root._fs, TEXT("Shell"));

		_root._entry = new ShellDirectory(GetDesktopFolder(), DesktopFolderPath(), hwnd);
		const ShellChildWndInfo& shell_info = static_cast<const ShellChildWndInfo&>(info);
		entry = _root.read_tree(&*shell_info._shell_path);
		break;}
	}

	if (_root._entry) {
		if (info._etype != ET_SHELL)
			wsprintf(_root._entry->_data.cFileName, TEXT("%s - %s"), drv, _root._fs);
	/*@@else
			lstrcpy(_root._entry->_data.cFileName, TEXT("GetDesktopFolder"));*/

		_root._entry->_data.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;


		///@todo use OWM_ROOTED flag

		if (info._open_mode & OWM_EXPLORE)	///@todo Is not-explore-mode for FileChildWindow completely implemented?
			_left_hwnd = *(_left=new Pane(_hwnd, IDW_TREE_LEFT, IDW_HEADER_LEFT, _root._entry, true, COL_CONTENT));

		_right_hwnd = *(_right=new Pane(_hwnd, IDW_TREE_RIGHT, IDW_HEADER_RIGHT, NULL, false,
										COL_TYPE|COL_SIZE|COL_DATE|COL_TIME|COL_ATTRIBUTES|COL_INDEX|COL_LINKS|COL_CONTENT));
	}

	_header_wdths_ok = false;

	if (!_left_hwnd && !_right_hwnd)
		return;

	if (entry)
		set_curdir(entry);
	else if (_root._entry)
		set_curdir(_root._entry);

	if (_left_hwnd) {
		int idx = ListBox_FindItemData(_left_hwnd, ListBox_GetCurSel(_left_hwnd), _left->_cur);
		ListBox_SetCurSel(_left_hwnd, idx);
		//SetFocus(_left_hwnd);
	}

	 // store path into history
	if (info._path && *info._path)
		_url_history.push(info._path);
}
int CBCGPRecentFilesListBox::AddItem(const CString& strFilePath, UINT nCmd, BOOL bPin)
{
	if (strFilePath.IsEmpty())
	{
		return -1;
	}

	TCHAR path[_MAX_PATH];   
	TCHAR name[_MAX_PATH];   
	TCHAR drive[_MAX_DRIVE];   
	TCHAR dir[_MAX_DIR];
	TCHAR fname[_MAX_FNAME];   
	TCHAR ext[_MAX_EXT];

#if _MSC_VER < 1400
	_tsplitpath (strFilePath, drive, dir, fname, ext);
	_tmakepath (path, drive, dir, NULL, NULL);
	_tmakepath (name, NULL, NULL, fname, ext);
#else
	_tsplitpath_s (strFilePath, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT);
	_tmakepath_s (path, drive, dir, NULL, NULL);
	_tmakepath_s (name, NULL, NULL, fname, ext);
#endif
	CString strItem;

	if (m_bFoldersMode)
	{
		CString strPath = path;
		if (strPath.GetLength() > 0 && 
			(strPath[strPath.GetLength() - 1] == _T('\\') || strPath[strPath.GetLength() - 1] == _T('/')))
		{
			strPath = strPath.Left(strPath.GetLength() - 1);
		}

		int nIndex = max(strPath.ReverseFind(_T('\\')), strPath.ReverseFind(_T('/')));
		if (nIndex >= 0)
		{
			strItem = strPath.Right(strPath.GetLength() - nIndex - 1);
		}
	}
	else
	{
		strItem = name;
	}

	strItem += _T("\n");
	strItem += path;

	int nIndex = -1;

	if (FindStringExact(-1, strItem) < 0)
	{
		nIndex = AddString(strItem);
		SetItemData(nIndex, (DWORD_PTR)nCmd);

		if (bPin)
		{
			SetItemPinned(nIndex);
		}

		CString strFile = m_bFoldersMode ? path : strFilePath;

		SHFILEINFO sfi;
		if (::SHGetFileInfo (strFile, 0, &sfi, sizeof(SHFILEINFO),
			SHGFI_ICON | SHGFI_SHELLICONSIZE | SHGFI_LARGEICON))
		{
			m_arIcons.Add(sfi.hIcon);
		}
		else
		{
			m_arIcons.Add(NULL);
		}
	}

	return nIndex;
}
Exemple #26
0
int CIPFilter::AddFromFile(LPCTSTR pszFilePath, bool bShowResponse)
{
	DWORD dwStart = GetTickCount();
	FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR);
	if (readFile != NULL)
	{
		enum EIPFilterFileType
		{
			Unknown = 0,
			FilterDat = 1,		// ipfilter.dat/ip.prefix format
			PeerGuardian = 2,	// PeerGuardian text format
			PeerGuardian2 = 3	// PeerGuardian binary format
		} eFileType = Unknown;

		setvbuf(readFile, NULL, _IOFBF, 32768);

		TCHAR szNam[_MAX_FNAME];
		TCHAR szExt[_MAX_EXT];
		_tsplitpath_s(pszFilePath, NULL, 0, NULL, 0, szNam, _countof(szNam), szExt, _countof(szExt));
		if (_tcsicmp(szExt, _T(".p2p")) == 0 || (_tcsicmp(szNam, _T("guarding.p2p")) == 0 && _tcsicmp(szExt, _T(".txt")) == 0))
			eFileType = PeerGuardian;
		else if (_tcsicmp(szExt, _T(".prefix")) == 0)
			eFileType = FilterDat;
		else
		{
			VERIFY( _setmode(_fileno(readFile), _O_BINARY) != -1 );
			static const BYTE _aucP2Bheader[] = "\xFF\xFF\xFF\xFFP2B";
			BYTE aucHeader[sizeof _aucP2Bheader - 1];
			if (fread(aucHeader, sizeof aucHeader, 1, readFile) == 1)
			{
				if (memcmp(aucHeader, _aucP2Bheader, sizeof _aucP2Bheader - 1)==0)
					eFileType = PeerGuardian2;
				else
				{
					(void)fseek(readFile, 0, SEEK_SET);
					VERIFY( _setmode(_fileno(readFile), _O_TEXT) != -1 ); // ugly!
				}
			}
		}

		int iFoundRanges = 0;
		int iLine = 0;
		if (eFileType == PeerGuardian2)
		{
			// Version 1: strings are ISO-8859-1 encoded
			// Version 2: strings are UTF-8 encoded
			uint8_t nVersion;
			if (fread(&nVersion, sizeof nVersion, 1, readFile)==1 && (nVersion==1 || nVersion==2))
			{
				while (!feof(readFile))
				{
					CHAR szName[256];
					int iLen = 0;
					for (;;) // read until NUL or EOF
					{
						int iChar = getc(readFile);
						if (iChar == EOF)
							break;
						if (iLen < sizeof szName - 1)
							szName[iLen++] = (CHAR)iChar;
						if (iChar == '\0')
							break;
					}
					szName[iLen] = '\0';
					
					uint32_t uStart;
					if (fread(&uStart, sizeof uStart, 1, readFile) != 1)
						break;
					uStart = ntohl(uStart);

					uint32_t uEnd;
					if (fread(&uEnd, sizeof uEnd, 1, readFile) != 1)
						break;
					uEnd = ntohl(uEnd);

					iLine++;
					// (nVersion == 2) ? OptUtf8ToStr(szName, iLen) : 
					AddIPRange(uStart, uEnd, DFLT_FILTER_LEVEL, CStringA(szName, iLen));
					iFoundRanges++;
				}
			}
		}
		else
		{
			CStringA sbuffer;
			CHAR szBuffer[1024];
			while (fgets(szBuffer, _countof(szBuffer), readFile) != NULL)
			{
				iLine++;
				sbuffer = szBuffer;
				
				// ignore comments & too short lines
				if (sbuffer.GetAt(0) == '#' || sbuffer.GetAt(0) == '/' || sbuffer.GetLength() < 5) {
					sbuffer.Trim(" \t\r\n");
					DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 );
					continue;
				}

				if (eFileType == Unknown)
				{
					// looks like html
					if (sbuffer.Find('>') > -1 && sbuffer.Find('<') > -1)
						sbuffer.Delete(0, sbuffer.ReverseFind('>') + 1);

					// check for <IP> - <IP> at start of line
					UINT u1, u2, u3, u4, u5, u6, u7, u8;
					if (sscanf_s(sbuffer, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8)
					{
						eFileType = FilterDat;
					}
					else
					{
						// check for <description> ':' <IP> '-' <IP>
						int iColon = sbuffer.Find(':');
						if (iColon > -1)
						{
							CStringA strIPRange = sbuffer.Mid(iColon + 1);
							UINT u1, u2, u3, u4, u5, u6, u7, u8;
							if (sscanf_s(strIPRange, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8)
							{
								eFileType = PeerGuardian;
							}
						}
					}
				}

				bool bValid = false;
				uint32_t start = 0;
				uint32_t end = 0;
				UINT level = 0;
				CStringA desc;
				if (eFileType == FilterDat)
					bValid = ParseFilterLine1(sbuffer, start, end, level, desc);
				else if (eFileType == PeerGuardian)
					bValid = ParseFilterLine2(sbuffer, start, end, level, desc);

				// add a filter
				if (bValid)
				{
					AddIPRange(start, end, level, desc);
					iFoundRanges++;
				}
				else
				{
					sbuffer.Trim(" \t\r\n");
					DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 );
				}
			}
		}
		fclose(readFile);

		// sort the IP filter list by IP range start addresses
		qsort(m_iplist.GetData(), m_iplist.GetCount(), sizeof(m_iplist[0]), CmpSIPFilterByStartAddr);

		// merge overlapping and adjacent filter ranges
		int iDuplicate = 0;
		int iMerged = 0;
		if (m_iplist.GetCount() >= 2)
		{
			// On large IP-filter lists there is a noticeable performance problem when merging the list.
			// The 'CIPFilterArray::RemoveAt' call is way too expensive to get called during the merging,
			// thus we use temporary helper arrays to copy only the entries into the final list which
			// are not get deleted.

			// Reserve a byte array (its used as a boolean array actually) as large as the current 
			// IP-filter list, so we can set a 'to delete' flag for each entry in the current IP-filter list.
			char* pcToDelete = new char[m_iplist.GetCount()];
			memset(pcToDelete, 0, m_iplist.GetCount());
			int iNumToDelete = 0;

			SIPFilter* pPrv = m_iplist[0];
			int i = 1;
			while (i < m_iplist.GetCount())
			{
				SIPFilter* pCur = m_iplist[i];
				if (   pCur->start >= pPrv->start && pCur->start <= pPrv->end	 // overlapping
					|| pCur->start == pPrv->end+1 && pCur->level == pPrv->level) // adjacent
				{
					if (pCur->start != pPrv->start || pCur->end != pPrv->end) // don't merge identical entries
					{
						//TODO: not yet handled, overlapping entries with different 'level'
						if (pCur->end > pPrv->end)
							pPrv->end = pCur->end;
						//pPrv->desc += _T("; ") + pCur->desc; // this may create a very very long description string...
						iMerged++;
					}
					else
					{
						// if we have identical entries, use the lowest 'level'
						if (pCur->level < pPrv->level)
							pPrv->level = pCur->level;
						iDuplicate++;
					}
					delete pCur;
					//m_iplist.RemoveAt(i);	// way too expensive (read above)
					pcToDelete[i] = 1;		// mark this entry as 'to delete'
					iNumToDelete++;
					i++;
					continue;
				}
				pPrv = pCur;
				i++;
			}

			// Create new IP-filter list which contains only the entries from the original IP-filter list
			// which are not to be deleted.
			if (iNumToDelete > 0)
			{
				CIPFilterArray newList;
				newList.SetSize(m_iplist.GetCount() - iNumToDelete);
				int iNewListIndex = 0;
				for (int i = 0; i < m_iplist.GetCount(); i++) {
					if (!pcToDelete[i])
						newList[iNewListIndex++] = m_iplist[i];
				}
				ASSERT( iNewListIndex == newList.GetSize() );

				// Replace current list with new list. Dump, but still fast enough (only 1 memcpy)
				m_iplist.RemoveAll();
				m_iplist.Append(newList);
				newList.RemoveAll();
				m_bModified = true;
			}
			delete[] pcToDelete;
		}

		if (thePrefs.GetVerbose())
		{
			DWORD dwEnd = GetTickCount();
			AddDebugLogLine(false, _T("Loaded IP filters from \"%s\""), pszFilePath);
			AddDebugLogLine(false, _T("Parsed lines/entries:%u  Found IP ranges:%u  Duplicate:%u  Merged:%u  Time:%s"), iLine, iFoundRanges, iDuplicate, iMerged, CastSecondsToHM((dwEnd-dwStart+500)/1000));
		}
		AddLogLine(bShowResponse, GetResString(IDS_IPFILTERLOADED), m_iplist.GetCount());
	}
	return static_cast<int>(m_iplist.GetCount());
}
Exemple #27
0
// Uploads the PNG file to Gyazo
BOOL uploadFile(HWND hwnd, LPCTSTR fileName, BOOL isPng)
{
	const int nSize = 256;
	LPCTSTR DEFAULT_UPLOAD_SERVER = _T("upload.gyazo.com");
	LPCTSTR DEFAULT_UPLOAD_PATH   = _T("/upload.cgi");
	LPCTSTR DEFAULT_UPLOAD_TOKEN = _T("");
	//LPCTSTR DEFAULT_USER_AGENT    = _T("User-Agent: Gyazowin/1.0\r\n");
	const int DEFAULT_UPLOAD_SERVER_PORT = INTERNET_DEFAULT_HTTP_PORT;

	TCHAR upload_server[nSize];
	TCHAR upload_path[nSize];
	TCHAR upload_token[nSize];
	//TCHAR ua[nSize];
	lstrcpy(upload_server, DEFAULT_UPLOAD_SERVER);
	lstrcpy(upload_path, DEFAULT_UPLOAD_PATH);
	lstrcpy(upload_token, DEFAULT_UPLOAD_TOKEN);
	//lstrcpy(ua, DEFAULT_USER_AGENT);
	int upload_server_port = DEFAULT_UPLOAD_SERVER_PORT;

	TCHAR runtime_path[MAX_PATH+1];
	TCHAR runtime_dirname[MAX_PATH+1];
	TCHAR config_file[MAX_PATH+1];
	if (0 != ::GetModuleFileName(NULL, runtime_path, MAX_PATH)) {
		TCHAR tmp[MAX_PATH+1];
		_tsplitpath_s(runtime_path, tmp, runtime_dirname, tmp, tmp);
	}
	lstrcpy(config_file, runtime_dirname);
	lstrcat(config_file, _T("\\gyazo.ini"));
	if (PathFileExists(config_file)) {
		LPCTSTR SECTION_NAME = _T("gyazo");
		GetPrivateProfileString(SECTION_NAME, _T("server"), DEFAULT_UPLOAD_SERVER, upload_server, sizeof(upload_server), config_file);
		GetPrivateProfileString(SECTION_NAME, _T("path"), DEFAULT_UPLOAD_PATH, upload_path, sizeof(upload_path), config_file);
		GetPrivateProfileString(SECTION_NAME, _T("token"), DEFAULT_UPLOAD_TOKEN, upload_token, sizeof(upload_token), config_file);
		//GetPrivateProfileString(SECTION_NAME, _T("user_agent"), DEFAULT_USER_AGENT, ua, sizeof(ua), config_file);
		upload_server_port = GetPrivateProfileInt(SECTION_NAME, _T("port"), DEFAULT_UPLOAD_SERVER_PORT, config_file);
	}

	const char*  sBoundary = "----BOUNDARYBOUNDARY----";		// boundary
	const char   sCrLf[]   = { 0xd, 0xa, 0x0 };					// 改行(CR+LF)
	TCHAR szHeader[200];

	StringCchPrintf(szHeader, 200, TEXT("Auth-Token: %s\r\nContent-type: multipart/form-data; boundary=----BOUNDARYBOUNDARY----"), upload_token);

	std::ostringstream	buf;	// 送信メッセージ

	wchar_t fname[_MAX_FNAME];
	wchar_t ext[_MAX_EXT];
	_wsplitpath(fileName, NULL, NULL, fname, ext );
	std::string data = (isPng) ? "imagedata" : "data";
	LPCTSTR file = (isPng) ? _T("gyazo") : wcsncat(fname, ext, _MAX_FNAME);
	size_t size = wcstombs(NULL, file, 0);
	char* CharStr = new char[size + 1];
	wcstombs(CharStr, file, size + 1);

	// -- "imagedata" part
	buf << "--";
	buf << sBoundary;
	buf << sCrLf;
	buf << "content-disposition: form-data; name=\"";
	buf << data;
	buf << "\"; filename=\"";
	buf << CharStr;
	buf << "\"";
	buf << sCrLf;
	//buf << "Content-type: image/png";	// 一応
	//buf << sCrLf;
	buf << sCrLf;

	// 本文: PNG ファイルを読み込む
	std::ifstream png;
	png.open(fileName, std::ios::binary);
	if (png.fail()) {
		MessageBox(hwnd, _T("PNG open failed"), szTitle, MB_ICONERROR | MB_OK);
		png.close();
		return FALSE;
	}
	buf << png.rdbuf();		// read all & append to buffer
	png.close();

	// 最後
	buf << sCrLf;
	buf << "--";
	buf << sBoundary;
	buf << "--";
	buf << sCrLf;

	// メッセージ完成
	std::string oMsg(buf.str());

	// WinInet を準備 (proxy は 規定の設定を利用)
	HINTERNET hSession    = InternetOpen(_T("Gyazowin/1.0"), 
		INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(NULL == hSession) {
		LastErrorMessageBox(hwnd, _T("Cannot configure wininet."));
		return FALSE;
	}
	
	// 接続先
	HINTERNET hConnection = InternetConnect(hSession, 
		upload_server, upload_server_port,
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if(NULL == hConnection) {
		LastErrorMessageBox(hwnd, _T("Cannot initiate connection."));
		InternetCloseHandle(hSession);
		return FALSE;
	}

	// 要求先の設定
	HINTERNET hRequest    = HttpOpenRequest(hConnection,
		_T("POST"), upload_path, NULL,
		NULL, NULL, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, NULL);
	if(NULL == hRequest) {
		LastErrorMessageBox(hwnd, _T("Cannot compose post request."));
		InternetCloseHandle(hConnection);
		InternetCloseHandle(hSession);
		return FALSE;
	}
	
	// 要求を送信
	BOOL bSuccess = FALSE;
	if (HttpSendRequest(hRequest,
                    szHeader,
					lstrlen(szHeader),
                    (LPVOID)oMsg.c_str(),
					(DWORD) oMsg.length()))
	{
		// 要求は成功
		
		DWORD resLen = 8;
		TCHAR resCode[8];

		// status code を取得
		if(!HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, resCode, &resLen, 0))
		{
			LastErrorMessageBox(hwnd, _T("Cannot get status code."));
			InternetCloseHandle(hRequest);
			InternetCloseHandle(hConnection);
			InternetCloseHandle(hSession);
			return FALSE;
		}

		// 結果 (URL) を読取る
		DWORD len;
		char  resbuf[1024];
		std::string result;

		// そんなに長いことはないけどまあ一応
		while (InternetReadFile(hRequest, (LPVOID)resbuf, 1024, &len)
			&& len != 0)
		{
			result.append(resbuf, len);
		}

		// 取得結果は NULL terminate されていないので
		result += '\0';

		if( _ttoi(resCode) != 200 ) {
			// upload 失敗 (status error)
			TCHAR errorBuf[200];
			StringCchPrintf(errorBuf, 200, TEXT("Cannot upload the image. Error %s "),resCode);
			std::wstring stemp = std::wstring(result.begin(), result.end());
			StringCchCat(errorBuf, 200, (LPTSTR)stemp.c_str());
			MessageBox(hwnd, errorBuf, szTitle, MB_ICONERROR | MB_OK);
		} else {
			// upload succeeded

			// クリップボードに URL をコピー
			setClipBoardText(result.c_str());
			
			// URL を起動
			execUrl(result.c_str()); 

			bSuccess = TRUE;
		}
	} else {
		// アップロード失敗...
		LastErrorMessageBox(hwnd, _T("Cannot connect to the server."));
	}

	// ハンドルクローズ
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnection);
	InternetCloseHandle(hSession);

	return bSuccess;

}
Exemple #28
0
bool 
FileUtils::mkdirs( 
    const String &path )
{
    bool res = false;
    ASSERT_D( path.length() > 0 );

#if defined(_WINDOWS) || defined(WIN32)

    TCHAR abspath[_MAX_PATH];
    TCHAR drive[_MAX_DRIVE];
    TCHAR dir[_MAX_DIR];
    TCHAR fname[_MAX_FNAME];
    TCHAR ext[_MAX_EXT];

    _tsplitpath_s( _tfullpath( abspath, path.c_str(), _MAX_PATH ), drive, dir, fname, ext );

    // remember the current drive
    int curDrive = _getdrive();

    // set the current drive
    _chdrive( toupper(drive[0]) - 'A' + 1 );

    // now start parsing out the path and create all directoried in the 
    // heirarchy
    String createPath;
    String dirStr(dir);
    dirStr += fname;
    StringUtils::trimBoth( FileUtils::PATH_SEP_PAT, dirStr );
    StringTokenizer tok(dirStr, FileUtils::PATH_SEP_PAT);
    while( tok.hasMoreTokens() )
    {
        createPath += FileUtils::PATH_SEP;
        createPath += tok.getNextToken();
        res = FileUtils::mkdir( createPath );
        if ( !res )
        {
            break;
        }
    }

    _chdrive( curDrive );

#else

    // the first step is to figure out where the path
    // starts. If the path contains a .. or . prefix, then
    // we have to calculate the start of the creation path
    // if it does not contain such prefix, then we'll just create
    // the directories relative to the current working directory

    String rootPath;
    String parsePath;

    String::size_type startPos = path.find_first_not_of( NTEXT("/.") );
    if ( startPos != 0 ) 
    {
        // there was at least one of these delimiters as a prefix
        String prefixStr( path, 0, startPos );

        rootPath = FileUtils::resolve( prefixStr );
        if ( rootPath.length() > 0 )
        {
            if ( rootPath[ rootPath.length() - 1 ] != NTEXT('/') )
            {
                rootPath += FileUtils::PATH_SEP;
            }
        }

        parsePath = path.substr( startPos );
    }
    else
    {
        // no delimiters, so just parse the path
        parsePath = path;
    }

    StringTokenizer tok( parsePath, FileUtils::PATH_SEP_PAT );
    while( tok.hasMoreTokens() )
    {
        rootPath += tok.getNextToken();
        rootPath += FileUtils::PATH_SEP;
        res = FileUtils::mkdir( rootPath );
        if ( !res )
        {
            break;
        }
    }
#endif

    return res;
}
/**
* Download and install from a remote location using HTTP.
* @param url the url indicating the location of the widget.
* @param widget receives the constructed widget on success.
*/
STDMETHODIMP CBondiWidgetLibrary::RemoteInstall(BSTR url, IBondiWidget** widget)
{
	HRESULT hRes = S_OK;

	try
	{
		TCHAR appDataPath[MAX_PATH];
		WidgetUtils::GetAppFolder(NULL,appDataPath);

		TCHAR canonicalURL[1024];
		DWORD nSize = 1024;
		InternetCanonicalizeUrl(url, canonicalURL, &nSize, ICU_BROWSER_MODE);

		// Check for an internet connection.
		if (InternetAttemptConnect(0) != ERROR_SUCCESS)
			BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("no internet connection found"));

		// Open a connection.
		HINTERNET hINet = InternetOpen(agentName,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE);

		if (hINet != 0)
		{
			HANDLE hConnection = ConnectToNetwork(25);
			if (hConnection != NULL)
			{
				// Attempt to access the resource at the url.
				DWORD options = INTERNET_FLAG_NEED_FILE|INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_RESYNCHRONIZE|INTERNET_FLAG_RELOAD;
				HINTERNET hFile = InternetOpenUrl( hINet, canonicalURL, NULL, 0, options, 0 );

				if (hFile != 0)
				{
					// Determine the file name to store the downloaded widget resource.
					TCHAR fName[MAX_PATH];
					_tsplitpath_s(url, NULL, 0, NULL, 0, fName, _MAX_FNAME, NULL, 0); 

					// Create the target local file.
					_bstr_t downloadPath = appDataPath + _bstr_t("\\") + _bstr_t(fName) + _bstr_t(".wgt");			
					HANDLE target = ::CreateFile(downloadPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

					// Read chunks.
					BYTE buffer[1024];
					DWORD dwRead;
					while (::InternetReadFile( hFile, buffer, 1024, &dwRead ) )
					{
						if ( dwRead == 0 )
							break;

						::WriteFile(target,buffer,dwRead,&dwRead,NULL);
					}

					::CloseHandle(target);

					InternetCloseHandle(hFile);

					CComObject<CBondiWidget>* newWidget;
					BONDI_CHECK_ERROR(CComObject<CBondiWidget>::CreateInstance(&newWidget),(IBondiWidgetLibrary*)this);
					newWidget->AddRef();

					// Do the installation.
					_bstr_t locale("en");
					hRes = newWidget->Install(downloadPath,locale,VARIANT_FALSE,VARIANT_FALSE);
					BONDI_CHECK_ERROR(hRes,(IBondiWidget*)newWidget);					

					if (hRes == S_OK)
					{
						// Set the install URL.
						CComPtr<IBondiWidgetAppConfig> appConfig;
						BONDI_CHECK_ERROR(newWidget->get_AppSettings(&appConfig),(IBondiWidget*)newWidget);
						if (appConfig != NULL)
							BONDI_CHECK_ERROR(appConfig->PutBondiSetting(_T("bondi.installUri"),canonicalURL,VARIANT_TRUE),appConfig);

						newWidget->InitialiseAppSettings();

						// We've finished with the temporary downloaded resource.
						::DeleteFile(downloadPath);

						*widget = (IBondiWidget*)newWidget;
					}
					else
					{
						// Didn't install (probably because of an existing widget).
						*widget = NULL;
					}
				}
				else
				{				 
					DWORD err = GetLastError();
					BONDI_RAISE_ERROR(E_BONDI_WIDGET_URL_OPEN_FAILED,_T("couldn't open url: ") + CString(canonicalURL));
				}

#ifdef UNDER_CE
				ConnMgrReleaseConnection(hConnection,1);
				CloseHandle(hConnection);
#endif
			}

			InternetCloseHandle(hINet);
		}
		else
		{
			BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("error opening internet connection"));
		}
	}
	catch (_com_error& err)
	{
		hRes = BONDI_SET_ERROR(err,"CBondiWidgetLibrary::RemoteInstall - COM exception");
	}
	catch (...)
	{
		hRes = BONDI_SET_ERROR(E_FAIL,"CBondiWidgetLibrary::RemoteInstall - C++ exception");
	}

	return hRes;
}
void	U2Filename::SplitPath(const TCHAR* szPath)
{
	_tsplitpath_s(szPath, m_drive, _MAX_DRIVE, m_dir, _MAX_DIR, 
		m_fname, _MAX_FNAME, m_ext, _MAX_EXT);
}