Exemple #1
0
String 
FileUtils::resolve( const String& source )
{
    ASSERT_D( source.length() > 0 );
#if defined(_WINDOWS) || defined(WIN32)
    TCHAR abspath[_MAX_PATH];
    return String(_tfullpath( abspath, source.c_str(), _MAX_PATH ));
#else

    char resolvedPath[MAXPATHLEN+1];
    resolvedPath[0] = '\0';

    String workingStr(resolveHome(source));

    ::realpath( workingStr.c_str(), resolvedPath );

    if ( errno == ENOENT )
    {
        return workingStr;
    }
    else
    {
        return String(resolvedPath);
    }
#endif
}
Exemple #2
0
std::string GetExePath()
{
  static std::string dolphin_path;
  if (dolphin_path.empty())
  {
#ifdef _WIN32
    TCHAR dolphin_exe_path[2048];
    TCHAR dolphin_exe_expanded_path[MAX_PATH];
    GetModuleFileName(nullptr, dolphin_exe_path, ARRAYSIZE(dolphin_exe_path));
    if (_tfullpath(dolphin_exe_expanded_path, dolphin_exe_path,
                   ARRAYSIZE(dolphin_exe_expanded_path)) != nullptr)
      dolphin_path = TStrToUTF8(dolphin_exe_expanded_path);
    else
      dolphin_path = TStrToUTF8(dolphin_exe_path);
#elif defined(__APPLE__)
    dolphin_path = GetBundleDirectory();
    dolphin_path = dolphin_path.substr(0, dolphin_path.find_last_of("Dolphin.app/Contents/MacOS"));
#else
    char dolphin_exe_path[PATH_MAX];
    ssize_t len = ::readlink("/proc/self/exe", dolphin_exe_path, sizeof(dolphin_exe_path));
    if (len == -1 || len == sizeof(dolphin_exe_path))
    {
      len = 0;
    }
    dolphin_exe_path[len] = '\0';
    dolphin_path = dolphin_exe_path;
#endif
  }
  return dolphin_path;
}
Exemple #3
0
//絶対パスの取得
bool UtilGetAbsPathName(CString &_FullPath,LPCTSTR lpszFileName)
{
	ASSERT(lpszFileName&&_tcslen(lpszFileName)>0);
	if(!lpszFileName||_tcslen(lpszFileName)<=0){
		TRACE(_T("ファイル名が指定されていない\n"));
		return false;
	}

	//---絶対パス取得
	TCHAR szAbsPath[_MAX_PATH+1]={0};
	{
		TCHAR Buffer[_MAX_PATH+1]={0};	//ルートかどうかのチェックを行う
		_tcsncpy_s(Buffer,lpszFileName,_MAX_PATH);
		PathAddBackslash(Buffer);
		if(PathIsRoot(Buffer)){
			//ドライブ名だけが指定されている場合、
			//_tfullpathはそのドライブのカレントディレクトリを取得してしまう
			_tcsncpy_s(szAbsPath,lpszFileName,_MAX_PATH);
		}
		else if(!_tfullpath(szAbsPath,lpszFileName,_MAX_PATH)){
			TRACE(_T("絶対パス取得失敗\n"));
			return false;
		}
	}

	_FullPath=szAbsPath;
	return true;
}
Exemple #4
0
std::string& GetExeDirectory()
{
  static std::string DolphinPath;
  if (DolphinPath.empty())
  {
#ifdef _WIN32
    TCHAR Dolphin_exe_Path[2048];
    TCHAR Dolphin_exe_Clean_Path[MAX_PATH];
    GetModuleFileName(nullptr, Dolphin_exe_Path, 2048);
    if (_tfullpath(Dolphin_exe_Clean_Path, Dolphin_exe_Path, MAX_PATH) != nullptr)
      DolphinPath = TStrToUTF8(Dolphin_exe_Clean_Path);
    else
      DolphinPath = TStrToUTF8(Dolphin_exe_Path);
    DolphinPath = DolphinPath.substr(0, DolphinPath.find_last_of('\\'));
#else
    char Dolphin_exe_Path[PATH_MAX];
    ssize_t len = ::readlink("/proc/self/exe", Dolphin_exe_Path, sizeof(Dolphin_exe_Path));
    if (len == -1 || len == sizeof(Dolphin_exe_Path))
    {
      len = 0;
    }
    Dolphin_exe_Path[len] = '\0';
    DolphinPath = Dolphin_exe_Path;
    DolphinPath = DolphinPath.substr(0, DolphinPath.rfind('/'));
#endif
  }
  return DolphinPath;
}
Exemple #5
0
int browseForFolder(std::wstring const& initial_dir_arg)
{
    TCHAR selected_dir[MAX_PATH];
    TCHAR initial_dir[MAX_PATH];
    if(!initial_dir_arg.empty())
    {
        // SHBrowseForFolder doesn't like relative initial paths.
        _tfullpath(initial_dir, initial_dir_arg.c_str(), MAX_PATH);
    }
    else
    {
        GetCurrentDirectory(MAX_PATH, initial_dir);
    }

    BROWSEINFO br_info = { 0 };
    br_info.lParam = reinterpret_cast<LPARAM>(initial_dir); 
    br_info.lpfn = BrowseFolderCallback;
    br_info.lpszTitle = L"Please select a folder";
    br_info.ulFlags = BIF_SHAREABLE | BIF_USENEWUI;
    LPITEMIDLIST lpItem = SHBrowseForFolder(&br_info);

    if(lpItem != NULL && SHGetPathFromIDList(lpItem, selected_dir))
    {
        std::wcout << selected_dir << "\n";
        return 0;
    }
    else
    {
        return 1;
    }
}
Exemple #6
0
BOOL CFileFind::FindFile(LPCTSTR pstrName /* = NULL */,
	DWORD dwUnused /* = 0 */)
{
	UNUSED_ALWAYS(dwUnused);
	Close();
	m_pNextInfo = new WIN32_FIND_DATA;
	m_bGotLast = FALSE;

	if (pstrName == NULL)
		pstrName = _T("*.*");
	lstrcpy(((WIN32_FIND_DATA*) m_pNextInfo)->cFileName, pstrName);

	m_hContext = ::FindFirstFile(pstrName, (WIN32_FIND_DATA*) m_pNextInfo);

	if (m_hContext == INVALID_HANDLE_VALUE)
	{
		DWORD dwTemp = ::GetLastError();
		Close();
		::SetLastError(dwTemp);
		return FALSE;
	}

	LPTSTR pstrRoot = m_strRoot.GetBufferSetLength(_MAX_PATH);
	LPCTSTR pstr = _tfullpath(pstrRoot, pstrName, _MAX_PATH);

	// passed name isn't a valid path but was found by the API
	ASSERT(pstr != NULL);
	if (pstr == NULL)
	{
		m_strRoot.ReleaseBuffer(-1);
		Close();
		::SetLastError(ERROR_INVALID_NAME);
		return FALSE;
	}
	else
	{
		// find the last forward or backward whack
		LPTSTR pstrBack  = _tcsrchr(pstrRoot, '\\');
		LPTSTR pstrFront = _tcsrchr(pstrRoot, '/');

		if (pstrFront != NULL || pstrBack != NULL)
		{
			if (pstrFront == NULL)
				pstrFront = pstrRoot;
			if (pstrBack == NULL)
				pstrBack = pstrRoot;

			// from the start to the last whack is the root

			if (pstrFront >= pstrBack)
				*pstrFront = '\0';
			else
				*pstrBack = '\0';
		}
		m_strRoot.ReleaseBuffer(-1);
	}

	return TRUE;
}
Exemple #7
0
/////////////////////////////////////////////////////////////////////////////
// Description: Creates a relative path name, if possible.
//
// Parameters:
//   bBeginWithDot - Prepends the relative path with the a period and
// backslash. While possibly rendundant, this may be useful for some contexts
// of relative pathnames. If a relative path cannot be resolved, this
// parameter is ignored.
//
bool TCMakeRelativePath(LPCTSTR pszPath, LPCTSTR pszFrom, LPTSTR pszDest,
  int cchMaxDest, bool bBeginWithDot)
{
  // Ensure that input paths are absolute
  TCHAR szPathCopy[_MAX_PATH], szFromCopy[_MAX_PATH];
  if (!_tfullpath(szPathCopy, pszPath, sizeofArray(szPathCopy)))
    return false;
  if (!_tfullpath(szFromCopy, pszFrom, sizeofArray(szFromCopy)))
    return false;

  // Replace (in-place) forward slashes with backslashes in input paths
  TCReplaceText(szPathCopy, TEXT("/"), TEXT("\\"), szPathCopy, -1);
  TCReplaceText(szFromCopy, TEXT("/"), TEXT("\\"), szFromCopy, -1);

  // The From path MUST be a directory, not a filename, so append backslash
  if (TEXT('\\') != szFromCopy[_tcslen(szFromCopy) - 1])
    _tcscat(szFromCopy, TEXT("\\"));

  // Use COM monikers to create a relative path
  HRESULT hr;
  IBindCtxPtr pbc;
  IMonikerPtr pmkFrom, pmkPath, pmkRelative;
  LPOLESTR pszRelative = NULL;
  if (SUCCEEDED(hr = CreateFileMoniker(_bstr_t(szFromCopy), &pmkFrom))
    && SUCCEEDED(hr = CreateFileMoniker(_bstr_t(szPathCopy), &pmkPath))
    && S_OK == (hr = pmkFrom->RelativePathTo(pmkPath, &pmkRelative))
    && SUCCEEDED(hr = CreateBindCtx(0, &pbc))
    && SUCCEEDED(hr = pmkRelative->GetDisplayName(pbc, NULL, &pszRelative)))
  {
    if (bBeginWithDot)
    {
      TC_tcscpyn(pszDest, TEXT(".\\"), cchMaxDest);
      cchMaxDest -= 2;
      pszDest += 2;
    }
    TC_tcscpyn(pszDest, _bstr_t(pszRelative), cchMaxDest);
    CoTaskMemFree(pszRelative);
    return true;
  }

  // Could not make a relative path, copy the absolute path
  TC_tcscpyn(pszDest, szPathCopy, cchMaxDest);
  return false;
}
Exemple #8
0
stringT pws_os::fullpath(const stringT &relpath)
{
  stringT retval;
  TCHAR full[_MAX_PATH];

  wmemset(full, 0, sizeof(full)/sizeof(TCHAR));
  if (_tfullpath(full, relpath.c_str(), _MAX_PATH))
    retval = full;
  return retval;
}
Exemple #9
0
char * MakeCanonicalFileName (const char * fileName)
{
    char buffer [_MAX_PATH];
    char * result = StrDup (_tfullpath (buffer, fileName, _MAX_PATH));

    if (result != 0)
    {
        AnsiLower (result);
        slashToBackSlash (result);
    }

    return (result);
}
Exemple #10
0
std::string GetTempFilenameForAtomicWrite(const std::string &path)
{
	std::string abs = path;
#ifdef _WIN32
	TCHAR absbuf[MAX_PATH];
	if (_tfullpath(absbuf, UTF8ToTStr(path).c_str(), MAX_PATH) != nullptr)
		abs = TStrToUTF8(absbuf);
#else
	char absbuf[PATH_MAX];
	if (realpath(path.c_str(), absbuf) != nullptr)
		abs = absbuf;
#endif
	return abs + ".xxx";
}
void GetProfileDirectory(TCHAR* szMirandaDir, TCHAR* szPath, int cbPath)
{
	TCHAR szProfileDir[MAX_PATH], szExpandedProfileDir[MAX_PATH], szMirandaBootIni[MAX_PATH];

	lstrcpy(szMirandaBootIni,szMirandaDir);
	lstrcat(szMirandaBootIni,_T("\\mirandaboot.ini"));
	GetPrivateProfileString(_T("Database"),_T("ProfileDir"),_T("./Profiles"),szProfileDir,SIZEOF(szProfileDir),szMirandaBootIni);
	ExpandEnvironmentStrings(szProfileDir,szExpandedProfileDir,SIZEOF(szExpandedProfileDir));
	_tchdir(szMirandaDir);
	if(!_tfullpath(szPath,szExpandedProfileDir,cbPath))
		lstrcpyn(szPath,szMirandaDir,cbPath);
	if(szPath[lstrlen(szPath)-1]=='\\')
		szPath[lstrlen(szPath)-1] = 0;
}
Exemple #12
0
CString CFileEditCtrl::GetNextPathName(POSITION &pos)
{
	// Returns the file name at the specified position in the buffer.
	// The starting position is retrieved using the GetStartPosition() function.
	// The position is updated to point to the next file, or set to NULL if
	// there are no more files.
	ASSERT (pos);								// pos must not be NULL
	LPTSTR str = (LPTSTR)pos;					// str points to file name at pos
	TCHAR lpstrReturnString[_MAX_PATH];
	CString szTemp;
	if (str[1] == ':')
		szTemp = str;							// str contains complete path
	else
		szTemp = m_szFolder + str;				// build the path
	_tfullpath(lpstrReturnString, szTemp, _MAX_PATH);	// get absolute path from any relative paths
	str += _tcslen(str) + 1;					// set pos to next file
	pos = *str ? (POSITION)str : NULL;
	return (CString)lpstrReturnString;
}
Exemple #13
0
//フルパスかつ絶対パスの取得
PATHERROR UtilGetCompletePathName(CString &_FullPath,LPCTSTR lpszFileName)
{
	ASSERT(lpszFileName&&_tcslen(lpszFileName)>0);
	if(!lpszFileName||_tcslen(lpszFileName)<=0){
		TRACE(_T("ファイル名が指定されていない\n"));
		return PATHERROR_INVALID;
	}

	//---絶対パス取得
	TCHAR szAbsPath[_MAX_PATH+1]={0};
	{
		TCHAR Buffer[_MAX_PATH+1]={0};	//ルートかどうかのチェックを行う
		_tcsncpy_s(Buffer,lpszFileName,_MAX_PATH);
		PathAddBackslash(Buffer);
		if(PathIsRoot(Buffer)){
			//ドライブ名だけが指定されている場合、
			//_tfullpathはそのドライブのカレントディレクトリを取得してしまう
			_tcsncpy_s(szAbsPath,lpszFileName,_MAX_PATH);
		}
		else if(!_tfullpath(szAbsPath,lpszFileName,_MAX_PATH)){
			TRACE(_T("絶対パス取得失敗\n"));
			return PATHERROR_ABSPATH;
		}
	}

	if(!PathFileExists(szAbsPath)&&!PathIsDirectory(szAbsPath)){
		//パスがファイルもしくはディレクトリとして存在しないなら、エラーとする
		TRACE(_T("ファイルが存在しない\n"));
		return PATHERROR_NOTFOUND;
	}
	if(!GetLongPathName(szAbsPath,szAbsPath,_MAX_PATH)){
		TRACE(_T("ロングファイル名取得失敗\n"));
		return PATHERROR_LONGNAME;
	}
	_FullPath=szAbsPath;
	return PATHERROR_NONE;
}
Exemple #14
0
bool 
FileUtils::getAttributes(
    const String &source, 
    FileAttributes &outAttrs )
{
    bool res = false;
    ASSERT_D( source.length() > 0 );
#if defined(_WINDOWS) || defined(WIN32)

    // get the full path of the input source and get it's attributes
    WIN32_FILE_ATTRIBUTE_DATA attrs;
    TCHAR abspath[_MAX_PATH];
    String properSource = FileUtils::properName( _tfullpath( abspath, source.c_str(), _MAX_PATH ) );
    res = ::GetFileAttributesEx( properSource.c_str(), GetFileExInfoStandard, &attrs) == TRUE;
    if ( res )
    {
        // parse out the file name
        String::size_type pos = properSource.rfind(FileUtils::PATH_SEP);
        if ( pos != String::npos )
        {
            String name = properSource.substr( pos + 1 );
            outAttrs.setFileName( name );
        }
        else
        {
            outAttrs.setFileName( properSource );
        }

        // fill out the size and time structures
        outAttrs.setFileSize( attrs.nFileSizeLow );
        outAttrs.setFileSizeEx( attrs.nFileSizeHigh );

        FILETIME localFileTime;
        SYSTEMTIME sysTime;
        struct tm tmTime;

        if ( ::FileTimeToLocalFileTime( &attrs.ftCreationTime, &localFileTime ) )
        {
            if ( ::FileTimeToSystemTime( &localFileTime, &sysTime ) )
            {
                tmTime.tm_year= sysTime.wYear - 1900;
                tmTime.tm_mon  = sysTime.wMonth - 1;
                tmTime.tm_wday = sysTime.wDayOfWeek;
                tmTime.tm_mday = sysTime.wDay;
                tmTime.tm_hour = sysTime.wHour;
                tmTime.tm_min = sysTime.wMinute;
                tmTime.tm_sec = sysTime.wSecond;

                outAttrs.setCreateTime( tmTime );
            }
        }

        if ( ::FileTimeToLocalFileTime( &attrs.ftLastWriteTime, &localFileTime ) )
        {
            if ( ::FileTimeToSystemTime( &localFileTime, &sysTime ) )
            {
                tmTime.tm_year= sysTime.wYear - 1900;
                tmTime.tm_mon  = sysTime.wMonth - 1;
                tmTime.tm_wday = sysTime.wDayOfWeek;
                tmTime.tm_mday = sysTime.wDay;
                tmTime.tm_hour = sysTime.wHour;
                tmTime.tm_min = sysTime.wMinute;
                tmTime.tm_sec = sysTime.wSecond;

                outAttrs.setModifyTime( tmTime );
            }
        }

        // finally, fill out the attributes
        outAttrs.setArchive( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) == FILE_ATTRIBUTE_ARCHIVE );
        outAttrs.setCompressed( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) == FILE_ATTRIBUTE_COMPRESSED );
        outAttrs.setDirectory( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY );
        outAttrs.setHidden( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == FILE_ATTRIBUTE_HIDDEN );
        outAttrs.setOffline( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) == FILE_ATTRIBUTE_OFFLINE );
        outAttrs.setReadonly( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY );
        outAttrs.setTemp( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) == FILE_ATTRIBUTE_TEMPORARY );
        outAttrs.setSystem( ( attrs.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) == FILE_ATTRIBUTE_SYSTEM );
    }

#else

    String resolvedPath = FileUtils::resolve( source );
    if ( resolvedPath.length() > 0 )
    {
        struct stat buff;
        res =  ::stat( resolvedPath.c_str(), &buff ) == 0;
        if ( res )
        {
            String theFileName;
            if ( StringUtils::splitBack( 
                     FileUtils::PATH_SEP,
                     resolvedPath,
                     NULL, &theFileName ) )
            {
                outAttrs.setFileName( theFileName );
            }
            else
            {
                outAttrs.setFileName( resolvedPath );
            }
            
            outAttrs.setFileSize( buff.st_size );
            outAttrs.setFileSizeEx(0);
            
            struct tm tmTime;
            
            tmTime = *::gmtime( &buff.st_atime );
            outAttrs.setCreateTime( tmTime );
            
            tmTime = *::gmtime( &buff.st_mtime );    
            outAttrs.setModifyTime( tmTime );
            
            outAttrs.setArchive( !S_ISDIR(buff.st_mode) );
            outAttrs.setDirectory( S_ISDIR(buff.st_mode) );
            outAttrs.setHidden( theFileName[0] == NTEXT('.') );
            outAttrs.setReadonly( ( buff.st_mode & S_IWUSR) == 0 );

            outAttrs.setCompressed( false );
            outAttrs.setOffline( false );
            outAttrs.setTemp( false );
            outAttrs.setSystem( false );   
        }    
    }
    
#endif

    return res;

}
Exemple #15
0
/*
 * opendir
 *
 * Returns a pointer to a DIR structure appropriately filled in to begin
 * searching a directory.
 */
_TDIR * 
_topendir (const _TCHAR *szPath)
{
  _TDIR *nd;
  unsigned int rc;
  _TCHAR szFullPath[MAX_PATH];
	
  errno = 0;

  if (!szPath)
    {
      errno = EFAULT;
      return (_TDIR *) 0;
    }

  if (szPath[0] == _T('\0'))
    {
      errno = ENOTDIR;
      return (_TDIR *) 0;
    }

  /* Attempt to determine if the given path really is a directory. */
  rc = GetFileAttributes (szPath);
  if (rc == (unsigned int)-1)
    {
      /* call GetLastError for more error info */
      errno = ENOENT;
      return (_TDIR *) 0;
    }
  if (!(rc & FILE_ATTRIBUTE_DIRECTORY))
    {
      /* Error, entry exists but not a directory. */
      errno = ENOTDIR;
      return (_TDIR *) 0;
    }

  /* Make an absolute pathname.  */
  _tfullpath (szFullPath, szPath, MAX_PATH);

  /* Allocate enough space to store DIR structure and the complete
   * directory path given. */
  nd = (_TDIR *) malloc (sizeof (_TDIR) + (_tcslen(szFullPath) + _tcslen (SLASH) +
			 _tcslen(SUFFIX) + 1) * sizeof(_TCHAR));

  if (!nd)
    {
      /* Error, out of memory. */
      errno = ENOMEM;
      return (_TDIR *) 0;
    }

  /* Create the search expression. */
  _tcscpy (nd->dd_name, szFullPath);

  /* Add on a slash if the path does not end with one. */
  if (nd->dd_name[0] != _T('\0') &&
      nd->dd_name[_tcslen (nd->dd_name) - 1] != _T('/') &&
      nd->dd_name[_tcslen (nd->dd_name) - 1] != _T('\\'))
    {
      _tcscat (nd->dd_name, SLASH);
    }

  /* Add on the search pattern */
  _tcscat (nd->dd_name, SUFFIX);

  /* Initialize handle to -1 so that a premature closedir doesn't try
   * to call _findclose on it. */
  nd->dd_handle = -1;

  /* Initialize the status. */
  nd->dd_stat = 0;

  /* Initialize the dirent structure. ino and reclen are invalid under
   * Win32, and name simply points at the appropriate part of the
   * findfirst_t structure. */
  nd->dd_dir.d_ino = 0;
  nd->dd_dir.d_reclen = 0;
  nd->dd_dir.d_namlen = 0;
  memset (nd->dd_dir.d_name, 0, FILENAME_MAX);

  return nd;
}
Exemple #16
0
int _RTLENTRY _EXPFUNC _tstati64 (const _TCHAR *pathP, struct stati64 *bufP)
{
    WIN32_FIND_DATA ff;
    HANDLE      hfile;              /* file handle */
    _TCHAR      curdir[MAX_PATH];   /* current directory */
    _TCHAR      DriveChar;
    _TCHAR     *full = 0;
    _TCHAR     *ext;

    /* Assume it is a disk file and try to get the FindFirst info.
     */
    memset(bufP, 0, sizeof(struct stati64));   /* Zero the structure   */
    bufP->st_nlink = 1;

    if ((hfile = FindFirstFile(pathP, &ff)) == (HANDLE)-1)
    {
        /* Check for special case of ROOT directory
         */
        if ((_tcspbrk(pathP, _TEXT("\\/.")) != NULL) &&
           ((full = _tfullpath(NULL, pathP, 0)) != NULL) &&
           (_tcslen(full) == 3))
        {
            if (GetDriveType(full) < 2)
                return (__NTerror());

            bufP->st_mode = S_IFDIR;
            bufP->st_dev = bufP->st_rdev = _totupper(full[0]) - _TEXT('A') + 1;

            free(full);
            return 0;
        }
        else
            if (full)
                free (full);

        /* It may not be a disk file.  Try to open the file for reading
         * so we can find out the type of the file.
         */
        if ((hfile = CreateFile(pathP, GENERIC_READ,
                      FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                      OPEN_EXISTING, 0, NULL)) == (HANDLE)-1)
            return (__NTerror());

        /* Get the handle type to see if it is a character device or pipe.
         */
        bufP->st_mode = GetFileType(hfile) == FILE_TYPE_PIPE ? S_IFIFO : S_IFCHR;
        CloseHandle(hfile);
        return (0);
    }

    /* It it a disk file, convert the NT file info to a stat structure.
     */
    FindClose(hfile);
    _statcvt_i64(bufP, ff.dwFileAttributes, &ff.ftCreationTime,
             &ff.ftLastAccessTime, &ff.ftLastWriteTime, ff.nFileSizeHigh,
             ff.nFileSizeLow);

    /* If we're not pointing to a directory, then set the exec bit on
     * "executable" files.
     */

    if ((bufP->st_mode & S_IFDIR) == 0)
    {
        if ((ext = _tcsrchr(pathP, _TEXT('.'))) != NULL)
        {
            if (
                 _tcsicmp(ext, _TEXT(".bat")) == NULL ||
                 _tcsicmp(ext, _TEXT(".cmd")) == NULL ||
                 _tcsicmp(ext, _TEXT(".com")) == NULL ||
                 _tcsicmp(ext, _TEXT(".exe")) == NULL
               )
            {
                /* Microsoft marks these file types as executable, so we will
                 * too.
                 */
                bufP->st_mode |= S_IEXEC;
            }
        }
    }

    /* Determine the disk device by parsing the drive name.
     * If no drive name, assume current drive.
     */
    if (pathP[1] == _TEXT(':'))
        DriveChar = pathP[0];
    else
    {
        if (GetCurrentDirectory(sizeof(curdir), curdir) == 0)
            DriveChar = _TEXT('A');        /* reasonable default if failure */
        else
            DriveChar = curdir[0];
    }
    if (DriveChar >= 'a' && DriveChar <= 'z')
        bufP->st_dev = DriveChar - 'a';
    else if (DriveChar >= 'A' && DriveChar <= 'Z')
        bufP->st_dev = DriveChar - 'A';
    bufP->st_rdev = bufP->st_dev;
    return (0);
}
Exemple #17
0
bool CGLCG::LoadShader(const TCHAR *shaderFile)
{
	CCGShader cgShader;
	TCHAR shaderPath[MAX_PATH];
	TCHAR tempPath[MAX_PATH];
	CGprofile vertexProfile, fragmentProfile;
	GLenum error;

	if(!fboFunctionsLoaded) {
		MessageBox(NULL, TEXT("Your OpenGL graphics driver does not support framebuffer objects.\nYou will not be able to use CG shaders in OpenGL mode."), TEXT("CG Error"),
			MB_OK|MB_ICONEXCLAMATION);
        return false;
    }

	vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
	fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);

	cgGLDisableProfile(vertexProfile);
	cgGLDisableProfile(fragmentProfile);

	ClearPasses();

	if (shaderFile == NULL || *shaderFile==TEXT('\0'))
		return true;

	lstrcpy(shaderPath, shaderFile);
    ReduceToPath(shaderPath);

	SetCurrentDirectory(shaderPath);
	if(!cgShader.LoadShader(_tToChar(shaderFile)))
		return false;

	cgGLSetOptimalOptions(vertexProfile);
	cgGLSetOptimalOptions(fragmentProfile);

	/* insert dummy pass that will contain the original texture
	*/
	shaderPasses.push_back(shaderPass());

	for(CCGShader::passVector::iterator it=cgShader.shaderPasses.begin();
			it!=cgShader.shaderPasses.end();it++) {
		shaderPass pass;

		pass.scaleParams = it->scaleParams;
		/* if this is the last pass (the only one that can have CG_SCALE_NONE)
		   and no filter has been set use the GUI setting
		*/
		if(pass.scaleParams.scaleTypeX==CG_SCALE_NONE && !it->filterSet) {
			pass.linearFilter = GUI.BilinearFilter;
		} else {
			pass.linearFilter = it->linearFilter;
		}

        pass.frameCounterMod = it->frameCounterMod;

        pass.floatFbo = it->floatFbo;

		// paths in the meta file can be relative
		_tfullpath(tempPath,_tFromChar(it->cgShaderFile),MAX_PATH);
		char *fileContents = ReadShaderFileContents(tempPath);
		if(!fileContents)
			return false;

        // individual shader might include files, these should be relative to shader
        ReduceToPath(tempPath);
        SetCurrentDirectory(tempPath);

		pass.cgVertexProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
						vertexProfile, "main_vertex", NULL);

		checkForCgError("Compiling vertex program");

		pass.cgFragmentProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
							fragmentProfile, "main_fragment", NULL);

		checkForCgError("Compiling fragment program");

        // set path back for next pass
        SetCurrentDirectory(shaderPath);

		delete [] fileContents;
		if(!pass.cgVertexProgram || !pass.cgFragmentProgram) {
			return false;
		}
		cgGLLoadProgram(pass.cgVertexProgram);
		cgGLLoadProgram(pass.cgFragmentProgram);

		/* generate framebuffer and texture for this pass and apply
		   default texture settings
		*/
		glGenFramebuffers(1,&pass.fbo);
		glGenTextures(1,&pass.tex);
		glBindTexture(GL_TEXTURE_2D,pass.tex);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		shaderPasses.push_back(pass);
	}

	for(std::vector<CCGShader::lookupTexture>::iterator it=cgShader.lookupTextures.begin();it!=cgShader.lookupTextures.end();it++) {		
		lookupTexture tex;
		strcpy(tex.id,it->id);

		/* generate texture for the lut and apply specified filter setting
		*/
		glGenTextures(1,&tex.tex);
		glBindTexture(GL_TEXTURE_2D,tex.tex);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST);

		_tfullpath(tempPath,_tFromChar(it->texturePath),MAX_PATH);

		// simple file extension png/tga decision
		int strLen = strlen(it->texturePath);
		if(strLen>4) {
			if(!strcasecmp(&it->texturePath[strLen-4],".png")) {
				int width, height;
				bool hasAlpha;
				GLubyte *texData;
				if(loadPngImage(tempPath,width,height,hasAlpha,&texData)) {
					glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
					glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width,
						height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, texData);
					free(texData);
				}
			} else if(!strcasecmp(&it->texturePath[strLen-4],".tga")) {
				STGA stga;
				if(loadTGA(tempPath,stga)) {
					glPixelStorei(GL_UNPACK_ROW_LENGTH, stga.width);
					glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, stga.width,
						stga.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, stga.data);
				}
			}
		}
		lookupTextures.push_back(tex);
	}

	/* enable texture unit 1 for the lookup textures
	*/
	glClientActiveTexture(GL_TEXTURE1);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glTexCoordPointer(2,GL_FLOAT,0,lut_coords);
	glClientActiveTexture(GL_TEXTURE0);

	/* generate textures and set default values for the pref-filled PREV deque.
	*/
	for(int i=0;i<prevPasses.size();i++) {
		glGenTextures(1,&prevPasses[i].tex);
		glBindTexture(GL_TEXTURE_2D,prevPasses[i].tex);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,512,512,0,GL_RGB,GL_UNSIGNED_SHORT_5_6_5,NULL);
		glBindTexture(GL_TEXTURE_2D,0);
		prevPasses[i].textureSize.x = prevPasses[i].textureSize.y = prevPasses[i].textureSize.x = prevPasses[i].textureSize.y = 0;
		memset(prevPasses[i].texCoords,0,sizeof(prevPasses[i].texCoords));
	}

	shaderLoaded = true;
	
	return true;
}
Exemple #18
0
CL_String CL_PathHelp::make_absolute(
	const CL_String &base_path,
	const CL_String &relative_path,
	PathType path_type)
{
	CL_String base = normalize(base_path, path_type);
	CL_String relative = normalize(relative_path, path_type);
	if (path_type == path_type_file)
	{
		if (!is_absolute(base, path_type_file))
		{
			// make base_path absolute using current drive and directory
#ifdef WIN32
			TCHAR absolute_base[MAX_PATH];
			memset(absolute_base, 0, sizeof(TCHAR) * MAX_PATH);
			if (_tfullpath(absolute_base, CL_StringHelp::utf8_to_ucs2(base).c_str(), MAX_PATH) == 0)
				throw CL_Exception(cl_format("Unable to make base path absolute: %1", base_path));
			base = absolute_base;
#else
			char working_dir[1024];
			memset(working_dir, 0, 1024);
			if (getcwd(working_dir, 1024) == 0)
				throw CL_Exception("Unable to get current working directory!");
			base = add_trailing_slash(working_dir, path_type) + base;
#endif
		}

		CL_String base_location = get_location(base_path, path_type_file);
		CL_String relative_location = get_location(relative_path, path_type_file);
		if (relative_location.empty() || CL_StringHelp::compare(relative_location, base_location, true) == 0)
		{
			if (is_absolute(relative, path_type))
			{
				if (relative_location.empty())
					return base_location + relative;
				else
					return relative;
			}
			CL_String absolute = add_trailing_slash(base, path_type) + relative.substr(relative_location.length());
			return normalize(absolute, path_type);
		}
		else
		{
#ifdef WIN32
			if (is_absolute(relative, path_type))
				return relative;

			if (relative_location.length() == 2 && relative_location[1] == ':')
			{
				int drive = 0;
				if (relative_location[0] >= 'A' && relative_location[0] <= 'Z')
					drive = relative_location[0] - 'A' + 1;
				else if (relative_location[0] >= 'a' && relative_location[0] <= 'z')
					drive = relative_location[0] - 'a' + 1;
				else
					throw CL_Exception(cl_format("Invalid drive: %1", relative_location));
				TCHAR working_dir[MAX_PATH];
				memset(working_dir, 0, sizeof(TCHAR)*MAX_PATH);
				if (_tgetdcwd(drive, working_dir, MAX_PATH) == 0)
					throw CL_Exception(cl_format("Unable to get current working directory for %1!", relative_location));

				return add_trailing_slash(working_dir, path_type) + relative.substr(relative_location.length());
			}
			else
			{
				return relative; // UNC path
			}
#else
			throw CL_Exception("Error in CL_PathHelp::make_absolute");
#endif
		}
	}
	else
	{
		if (is_absolute(relative, path_type))
			return relative;
		CL_String absolute = add_trailing_slash(base, path_type) + relative;
		return normalize(absolute, path_type);
	}
}
Exemple #19
0
bool CD3DCG::LoadShader(const TCHAR *shaderFile)
{
	CCGShader cgShader;
	TCHAR shaderPath[MAX_PATH];
	TCHAR tempPath[MAX_PATH];
	HRESULT hr;
	GLenum error;

	ClearPasses();

	if (shaderFile == NULL || *shaderFile==TEXT('\0'))
		return true;

	lstrcpy(shaderPath,shaderFile);
	for(int i=lstrlen(shaderPath); i>=0; i--){
		if(IS_SLASH(shaderPath[i])){
			shaderPath[i]=TEXT('\0');
			break;
		}
	}

	SetCurrentDirectory(shaderPath);
	if(!cgShader.LoadShader(_tToChar(shaderFile)))
		return false;

	CGprofile vertexProfile = cgD3D9GetLatestVertexProfile();
	CGprofile pixelProfile = cgD3D9GetLatestPixelProfile();

	const char** vertexOptions = cgD3D9GetOptimalOptions(vertexProfile);
	const char** pixelOptions = cgD3D9GetOptimalOptions(pixelProfile);

	shaderPasses.push_back(shaderPass());

	for(CCGShader::passVector::iterator it=cgShader.shaderPasses.begin();
			it!=cgShader.shaderPasses.end();it++) {
		shaderPass pass;

		pass.scaleParams = it->scaleParams;
		/* if this is the last pass (the only one that can have CG_SCALE_NONE)
		   and no filter has been set use the GUI setting
		*/
		if(pass.scaleParams.scaleTypeX==CG_SCALE_NONE && !it->filterSet) {
			pass.linearFilter = GUI.BilinearFilter;
		} else {
			pass.linearFilter = it->linearFilter;
		}

		// paths in the meta file can be relative
		_tfullpath(tempPath,_tFromChar(it->cgShaderFile),MAX_PATH);
		char *fileContents = ReadShaderFileContents(tempPath);
		if(!fileContents)
			return false;

		pass.cgVertexProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
						vertexProfile, "main_vertex", vertexOptions);

		checkForCgError("Compiling vertex program");

		pass.cgFragmentProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
						pixelProfile, "main_fragment", pixelOptions);

		checkForCgError("Compiling fragment program");

		delete [] fileContents;
		if(!pass.cgVertexProgram || !pass.cgFragmentProgram) {
			return false;
		}
		if(pass.cgVertexProgram) {
			hr = cgD3D9LoadProgram(pass.cgVertexProgram,false,0);
		}
		checkForCgError("Loading vertex program");
		if(pass.cgFragmentProgram) {
			hr = cgD3D9LoadProgram(pass.cgFragmentProgram,false,0);
		}
		checkForCgError("Loading fragment program");

		/* generate vertex buffer
		*/
		
		hr = pDevice->CreateVertexBuffer(sizeof(VERTEX)*4,D3DUSAGE_WRITEONLY,0,D3DPOOL_MANAGED,&pass.vertexBuffer,NULL);
		if(FAILED(hr)) {
			pass.vertexBuffer = NULL;
			DXTRACE_ERR_MSGBOX(TEXT("Error creating vertex buffer"), hr);
			return false;
		}

		/* set up vertex declarations for the pass,
		   this also creates the vertex declaration
		*/
		setupVertexDeclaration(pass);

		shaderPasses.push_back(pass);
	}

	for(std::vector<CCGShader::lookupTexture>::iterator it=cgShader.lookupTextures.begin();it!=cgShader.lookupTextures.end();it++) {		
		lookupTexture tex;
		strcpy(tex.id,it->id);
		tex.linearFilter = it->linearfilter;

		_tfullpath(tempPath,_tFromChar(it->texturePath),MAX_PATH);

		hr = D3DXCreateTextureFromFileEx(
               pDevice,
               tempPath,
               D3DX_DEFAULT_NONPOW2,
               D3DX_DEFAULT_NONPOW2,
               0,
               0,
               D3DFMT_FROM_FILE,
               D3DPOOL_MANAGED,
			   it->linearfilter?D3DX_FILTER_LINEAR:D3DX_FILTER_POINT,
               0,
               0,
               NULL,
               NULL,
               &tex.tex);
		if FAILED(hr){
			tex.tex = NULL;
		}
		lookupTextures.push_back(tex);
	}

	shaderLoaded = true;

	return true;
}
Exemple #20
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;
}
Exemple #21
0
void CFileEditCtrl::FillBuffers()
{
	// initializes the m_szFolder and m_lpstrFiles member variables
	// these variables are used by the GetStartPosition() and 
	// GetNextPathName() functions to retrieve the file names entered
	// by the user.
	ASSERT(IsWindow(this));						// Control window must exist
#if defined FEC_NORESOURCESTRINGS
	m_szFolder = FEC_IDS_SEPERATOR;
#else
	m_szFolder.LoadString(FEC_IDS_SEPERATOR);
#endif
	TCHAR chSeperator = m_szFolder[0];			// get the character used to seperate the files

	m_szFolder.Empty();							// empty the buffers of old data
	if (m_lpstrFiles)
	{
		delete m_lpstrFiles;
		m_lpstrFiles = NULL;
	}

	int len = GetWindowTextLength();
	if (!len)									// no files entered, leave buffers empty
		return;
	LPTSTR lpstrWindow = new TCHAR[len + 1];	// working buffer
	GetWindowText(lpstrWindow, len + 1);
	LPTSTR lpstrStart = lpstrWindow;			// points to the first character in a file name
	LPTSTR lpstrEnd = NULL;						// points to the next seperator character
	while(*lpstrStart == chSeperator || _istspace(*lpstrStart))
		lpstrStart++;							// skip over leading spaces and seperator characters
	if (!*lpstrStart)
	{											// no files entered, leave buffers empty
		delete lpstrWindow;
		return;
	}
	lpstrEnd = _tcschr(lpstrStart, chSeperator);// find seperator character
	if (lpstrEnd)								// mark end of string
		*lpstrEnd = 0;
	if (!lpstrEnd || m_bFindFolder || (!m_bFindFolder && !(m_pCFileDialog->m_ofn.Flags & OFN_ALLOWMULTISELECT)))
//	if (only one entry || find folder || (find file && find only one file))
	{
		m_lpstrFiles = new TCHAR[_MAX_PATH];
		ZeroMemory(m_lpstrFiles,_MAX_PATH);
		_tfullpath(m_lpstrFiles, lpstrStart, _MAX_PATH); // get absolute path
/////////////////////////////////////////////////////////////////////////////////////
// uncomment this code to add a trailing slash to folders if it is not already there
//		int len = _tcslen(m_lpstrFiles);
//		if (m_bFindFolder && m_lpstrFiles[len - 1] != 0x5c)
//			m_lpstrFiles[len] = 0x5c;
/////////////////////////////////////////////////////////////////////////////////////
		delete lpstrWindow;
		return;
	}
	_TCHAR Drive[_MAX_DRIVE];
	_TCHAR Folder[_MAX_PATH];
	_TCHAR File[_MAX_PATH];
	_TCHAR Ext[_MAX_PATH];
	_tsplitpath(lpstrStart, Drive, Folder, File, Ext);
	m_szFolder = (CString)Drive + Folder;		// drive and directory placed in m_szFolder
	m_lpstrFiles = new TCHAR[len + 1];
	ZeroMemory(m_lpstrFiles, len + 1);
	_tcscpy(m_lpstrFiles, File);				// file and extension of first file placed in m_lpstrFiles
	_tcscat(m_lpstrFiles, Ext);
	lpstrStart = lpstrEnd + 1;					// reset to the start of the next string
	LPTSTR pointer = m_lpstrFiles + _tcslen(m_lpstrFiles) + 1;	// location where next file will be placed in m_lpstrFiles
	while (lpstrEnd)
	{	// add the rest of the files m_lpstrFiles as they have been typed (include any path information)
		while(*lpstrStart == chSeperator || _istspace(*lpstrStart))
			lpstrStart++;						// remove leading spaces and seperator characters
		if (!*lpstrStart)						// last file was followed by spaces and seperator characters,
			break;								// there are no more files entered
		lpstrEnd = _tcschr(lpstrStart, chSeperator); // find next seperator character
		if (lpstrEnd)
			*lpstrEnd = 0;		// mark end of string
		_tcscpy(pointer, lpstrStart);			// copy string to its location in m_lpstrFiles
		pointer += _tcslen(pointer) + 1;		// reset pointer to accept next file
		if (lpstrEnd)
			lpstrStart = lpstrEnd + 1;			// reset to the start of the next string
	}
	delete lpstrWindow;							// delete working buffer
}
Exemple #22
0
HANDLE WINAPI EXP_NAME(OpenPlugin)(int openFrom, INT_PTR item)
{
    PCTSTR filePath;
    auto_ptr<wchar_t> cmdLine;
    auto_ptr<PluginPanelItem> panelItem;
    switch(openFrom) {
        case OPEN_COMMANDLINE:
            {
            if(!item)
                return INVALID_HANDLE_VALUE;
#ifdef FAR3
            cmdLine.reset(_wcsdup(((OpenCommandLineInfo*)item)->CommandLine));
            filePath  = cmdLine.get();
#else
            filePath = (PCTSTR)item;
#endif
            if(!filePath || !*filePath)
	        return INVALID_HANDLE_VALUE;

            if(*filePath == '\"') {
                PTSTR p1 = const_cast<PTSTR>(filePath) + _tcslen(filePath) - 1;
                if(*p1 == '\"')
                    *p1 = 0;
                memmove(const_cast<PTSTR>(filePath), filePath + 1, (p1 - filePath + 1) * sizeof(TCHAR));
            }
            }
            break;

        case OPEN_PLUGINSMENU:
            {
            //assert(item->)
            filePath = JsonPlugin::ClipboardName;
            /*panelItem.reset(GetCurrentItem());
            panelItem->FileName;
            if(!filePath || !*filePath)
                return INVALID_HANDLE_VALUE;*/                
            }
            break;

#ifdef FAR3
        case OPEN_SHORTCUT:
            if(!item)
                return INVALID_HANDLE_VALUE;
	        filePath = ((OpenShortcutInfo*)item)->HostFile;
                break;
#endif
        default:
	    return INVALID_HANDLE_VALUE;
    }

	//SaveScreen ss;
	//PCTSTR Items[]={_T(""),GetMsg(MLoading)};
	//Message(0,NULL,Items,_countof(Items),0);

    // These command lines are possible:
    //   file.json
    //   c:\dir\file.json
    //???   http://site.com/url

    tstring sFilePath( 
#ifdef FAR3
        openFrom == OPEN_SHORTCUT ? ((OpenShortcutInfo*)item)->HostFile : 
#endif
                    filePath);
    tstring sSubDir;
    if(openFrom == OPEN_COMMANDLINE) {
        tstring sCommandLine(filePath);
        size_t colon = sCommandLine.find(':');
        if(colon != tstring::npos) {
            tstring s1 = sCommandLine.substr(0, colon);
            if(GetFileAttributes(s1.c_str()) != 0xffffffff) { // file before 1st colon exists, get the rest 
                sFilePath = s1;
                sSubDir = sCommandLine.substr(colon+1);
            } else {
                colon = sCommandLine.find(':', colon+1);
                sFilePath = sCommandLine.substr(0, colon);
                if(colon != tstring::npos) // second colon exists, get the rest
                    sSubDir = sCommandLine.substr(colon+1);
            }
        }
        TCHAR absPath[MAX_PATH];
#ifdef UNICODE
        if(!wcschr(sFilePath.c_str(), ':')) // if rel path, convert it
        {
            StartupInfo.FSF->ConvertPath(CPM_FULL, sFilePath.c_str(), absPath, _countof(absPath));
#else
        if(GetFileAttributes(sFilePath.c_str()) != 0xffffffff) { // if local file exists, use its abs path
	    _tfullpath(absPath, sFilePath.c_str(), _countof(absPath));
#endif
            sFilePath = absPath;
        }
    }
    JsonPlugin* plugin;
    try
    {
        plugin = new JsonPlugin(sFilePath.c_str());
    }
    catch(WinExcept ex)
    {
        WinError(ex);
        return INVALID_HANDLE_VALUE;
    }
    if(plugin->HasParseError()) {
        auto error = plugin->GetParseError();
        auto eroffs = plugin->GetErrorOffset();
        delete plugin;
        tstring err(GetMsg(error + MParseErrorNone - kParseErrorNone));
        err += '\n';
        LPCTSTR err2 = GetMsg(MParseOffset);
        vector<TCHAR> err3(_tcslen(err2) + 20);
        _sntprintf(&err3[0], err3.size()-1, err2, eroffs); err3[err3.size()-1] = 0;
        err += &err3[0];
        WinError(err.c_str());
        return INVALID_HANDLE_VALUE;
    }
    if(!sSubDir.empty())
	try {
        plugin->SetDirectory(sSubDir.c_str(),0);
	}
	catch(...) {}
    return plugin;
}

#ifdef FAR3
HANDLE WINAPI AnalyseW(const AnalyseInfo *info)
{
    HANDLE h = OpenFilePluginW(info->FileName, (BYTE*)info->Buffer, (int)info->BufferSize, (int)info->OpMode);
    return h == INVALID_HANDLE_VALUE ? NULL : h;
}
Exemple #23
0
// ---
BOOL CAvpFileFindW::FindFile(LPCWSTR pstrName /* = NULL */,	DWORD dwUnused /* = 0 */) {
	Close();
	m_pNextInfo = new WIN32_FIND_DATAW;
	m_bGotLast = FALSE;

	if (pstrName == NULL)
		pstrName = L"*.*";
/*
	if ( (wcslen(pstrName) + 1) > _countof(((WIN32_FIND_DATAW*) m_pNextInfo)->cFileName) )
		// Это ошибка, конечно. В этом случае мы все равно ничего не найдем. Но, наверное, нужно выполнять
		// поиск с переходом в каталог
		return FALSE;

	wcscpy(((WIN32_FIND_DATAW*) m_pNextInfo)->cFileName, pstrName);
*/
#if defined(_UNICODE)
	m_hContext = ::FindFirstFile(pstrName, (WIN32_FIND_DATAW*) m_pNextInfo);
#else
	if ( g_bUnicodePlatform )
		m_hContext = ::FindFirstFileW(pstrName, (WIN32_FIND_DATAW*) m_pNextInfo);
	else {
		WIN32_FIND_DATAA rcContext;
		//::WContext2AContext( (WIN32_FIND_DATAW*) m_pNextInfo, &rcContext );
		CAPointer<char> pConverted = ::UnicodeToMbcs( pstrName );
		m_hContext = ::FindFirstFileA( pConverted, &rcContext );
		::AContext2WContext( &rcContext, (WIN32_FIND_DATAW*) m_pNextInfo );
	}
#endif

	if (m_hContext == INVALID_HANDLE_VALUE)	{
		DWORD dwTemp = ::GetLastError();
		Close();
		::SetLastError(dwTemp);
		return FALSE;
	}

#if 0 // Dont use this technique - \\?\ problem
	LPWSTR pstrRoot = m_strRoot;
	LPCWSTR pstr = NULL;
#if defined(_UNICODE)
	pstr = _tfullpath(pstrRoot, pstrName, _countof(m_strRoot));
#else
	if ( g_bUnicodePlatform )
		pstr = _wfullpath(pstrRoot, pstrName, _countof(m_strRoot));
	else {
		CAPointer<char> pConverted = ::UnicodeToMbcs( pstrName );
		CHAR strRoot[_MAX_PATH];
		LPCSTR pAStr = _fullpath(strRoot, pConverted, _countof(strRoot));
		if ( pAStr ) {
			::MbcsToUnicode( strRoot, pstrRoot, _countof(m_strRoot) );
			pstr = pstrRoot;
		}
	}
#endif

	// passed name isn't a valid path but was found by the API
	if (pstr == NULL)	{
		Close();
		::SetLastError(ERROR_INVALID_NAME);
		return FALSE;
	}
	else {
		// find the last forward or backward whack
		LPWSTR pstrBack  = wcsrchr(pstrRoot, L'\\');
		LPWSTR pstrFront = wcsrchr(pstrRoot, L'/');

		if (pstrFront != NULL || pstrBack != NULL) {
			if (pstrFront == NULL)
				pstrFront = pstrRoot;
			if (pstrBack == NULL)
				pstrBack = pstrRoot;

			// from the start to the last whack is the root

			if (pstrFront >= pstrBack)
				*pstrFront = L'\0';
			else
				*pstrBack = L'\0';
		}
	}
#endif
	return TRUE;
}