Beispiel #1
0
QIcon QFileIconProvider::icon(const QFileInfo &info) const
{
    Q_D(const QFileIconProvider);

    QIcon platformIcon = qt_guiPlatformPlugin()->fileSystemIcon(info);
    if (!platformIcon.isNull())
        return platformIcon;

#if defined(Q_WS_X11) && !defined(QT_NO_STYLE_GTK)
    if (X11->desktopEnvironment == DE_GNOME) {
        QIcon gtkIcon = QGtkStylePrivate::getFilesystemIcon(info);
        if (!gtkIcon.isNull())
            return gtkIcon;
    }
#endif

#ifdef Q_WS_MAC
    QIcon retIcon = d->getMacIcon(info);
    if (!retIcon.isNull())
        return retIcon;
#elif defined Q_WS_WIN
    QIcon icon = d->getWinIcon(info);
    if (!icon.isNull())
        return icon;
#elif defined Q_WS_HAIKU
    QIcon icon = d->getHaikuIcon(info);
    if (!icon.isNull())
        return icon;
#endif
    if (info.isRoot())
#if defined (Q_WS_WIN) && !defined(Q_WS_WINCE)
    {
        UINT type = GetDriveType((wchar_t *)info.absoluteFilePath().utf16());

        switch (type) {
        case DRIVE_REMOVABLE:
            return d->getIcon(QStyle::SP_DriveFDIcon);
        case DRIVE_FIXED:
            return d->getIcon(QStyle::SP_DriveHDIcon);
        case DRIVE_REMOTE:
            return d->getIcon(QStyle::SP_DriveNetIcon);
        case DRIVE_CDROM:
            return d->getIcon(QStyle::SP_DriveCDIcon);
        case DRIVE_RAMDISK:
        case DRIVE_UNKNOWN:
        case DRIVE_NO_ROOT_DIR:
        default:
            return d->getIcon(QStyle::SP_DriveHDIcon);
        }
    }
#else
    return d->getIcon(QStyle::SP_DriveHDIcon);
#endif
    if (info.isFile()) {
        if (info.isSymLink())
            return d->getIcon(QStyle::SP_FileLinkIcon);
        else
            return d->getIcon(QStyle::SP_FileIcon);
    }
  if (info.isDir()) {
    if (info.isSymLink()) {
      return d->getIcon(QStyle::SP_DirLinkIcon);
    } else {
      if (info.absoluteFilePath() == d->homePath) {
        return d->getIcon(QStyle::SP_DirHomeIcon);
      } else {
        return d->getIcon(QStyle::SP_DirIcon);
      }
    }
  }
  return QIcon();
}
Beispiel #2
0
void Engine::checkCD() {
#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__SYMBIAN32__)
	// It is a known bug under Windows that games that play CD audio cause
	// ScummVM to crash if the data files are read from the same CD. Check
	// if this appears to be the case and issue a warning.

	// If we can find a compressed audio track, then it should be ok even
	// if it's running from CD.

#ifdef USE_VORBIS
	if (Common::File::exists("track1.ogg") ||
	    Common::File::exists("track01.ogg"))
		return;
#endif
#ifdef USE_FLAC
	if (Common::File::exists("track1.fla") ||
            Common::File::exists("track1.flac") ||
	    Common::File::exists("track01.fla") ||
	    Common::File::exists("track01.flac"))
		return;
#endif
#ifdef USE_MAD
	if (Common::File::exists("track1.mp3") ||
	    Common::File::exists("track01.mp3"))
		return;
#endif

	char buffer[MAXPATHLEN];
	int i;

	const Common::FSNode gameDataDir(ConfMan.get("path"));

	if (gameDataDir.getPath().empty()) {
		// That's it! I give up!
		if (getcwd(buffer, MAXPATHLEN) == NULL)
			return;
	} else
		Common::strlcpy(buffer, gameDataDir.getPath().c_str(), sizeof(buffer));

	for (i = 0; i < MAXPATHLEN - 1; i++) {
		if (buffer[i] == '\\')
			break;
	}

	buffer[i + 1] = 0;

	if (GetDriveType(buffer) == DRIVE_CDROM) {
		GUI::MessageDialog dialog(
			_("You appear to be playing this game directly\n"
			"from the CD. This is known to cause problems,\n"
			"and it is therefore recommended that you copy\n"
			"the data files to your hard disk instead.\n"
			"See the README file for details."), _("OK"));
		dialog.runModal();
	} else {
		// If we reached here, the game has audio tracks,
		// it's not ran from the CD and the tracks have not
		// been ripped.
		GUI::MessageDialog dialog(
			_("This game has audio tracks in its disk. These\n"
			"tracks need to be ripped from the disk using\n"
			"an appropriate CD audio extracting tool in\n"
			"order to listen to the game's music.\n"
			"See the README file for details."), _("OK"));
		dialog.runModal();
	}
#endif
}
Beispiel #3
0
Driver *CFileServer::GetDrivers(int &Count)
{
	try
	{
		TCHAR szDrivesList[256]; // Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL>"
		TCHAR szDrive[4];
		TCHAR szTheDrive[32];
		// TCHAR szName[255];
		TCHAR szType[16];
		UINT nType = 0;
		DWORD dwLen;
		int nIndex = 0;
		dwLen = GetLogicalDriveStrings(256, szDrivesList);
		Driver *driver = NULL;
		Driver *p = NULL;
		int k = 0;

		//Add the desktop to the driver list
		driver = new Driver;
		if(StrCmp(gl_strLanguageId, CHINESE) == 0)
			sprintf_s(driver->DriverName, "%s", szDesktop_CH);
		else
			sprintf_s(driver->DriverName, "%s", szDesktop_EN);
		p = driver;
		k ++;
		if(StrCmp(gl_strLanguageId, CHINESE) == 0)
			sprintf_s(szType, "%s", szLocalDisk_CH);
		else
			sprintf_s(szType, "%s", szLocalDisk_EN);


		// Parse the list of drives	
		while (nIndex < (int)(dwLen - 3))
		{
			strcpy_s(szDrive, szDrivesList + nIndex);
			nIndex += 4;
			szDrive[2] = '\0'; // remove the '\'
			sprintf_s(szTheDrive, "(%s)", szDrive);

			// szName[0] = '\0';
			szType[0] = '\0';

			strcat_s(szDrive, "\\");

			// GetVolumeInformation(szDrive, szName, sizeof(szName), NULL, NULL, NULL, NULL, NULL);

			// Get infos on the Drive (type and Name)
			nType = GetDriveType(szDrive);
			switch (nType)
			{
			case DRIVE_FIXED:
				if(StrCmp(gl_strLanguageId, CHINESE) == 0)
					sprintf_s(szType, "%s", szLocalDisk_CH);
				else
					sprintf_s(szType, "%s", szLocalDisk_EN);
				break;

			case DRIVE_REMOVABLE:
				if(StrCmp(gl_strLanguageId, CHINESE) == 0)
					sprintf_s(szType, "%s", szFloppy_CH);
				else
					sprintf_s(szType, "%s", szFloppy_EN);
				break;

			case DRIVE_CDROM:
				sprintf_s(szType, "%s", "CD-ROM");
				break;

			case DRIVE_REMOTE:
				if(StrCmp(gl_strLanguageId, CHINESE) == 0)
					sprintf_s(szType, "%s", szNetDriver_CH);
				else
					sprintf_s(szType, "%s", szNetDriver_EN);
				break;

			default:
				if(StrCmp(gl_strLanguageId, CHINESE) == 0)
					sprintf_s(szType, "%s", szUnknowDriver_CH);
				else
					sprintf_s(szType, "%s", szUnknowDriver_EN);
				break;
			}

			// Prepare it for Combo Box and add it
			strcat_s(szTheDrive, " - ");
			strcat_s(szTheDrive, szType);

			Driver *newDriver = new Driver;
			sprintf_s(newDriver->DriverName, szTheDrive);
			if(NULL == driver)
			{
				driver = newDriver;
				p = driver;
			}
			else
			{
				p->next = newDriver;
				p = newDriver;
			}
			k++;
		}
		Count = k;
		return driver;
	}
	catch(...)
	{
		if (gl_pLogger)
			gl_pLogger->log_info("CFileServer::GetDrivers() unkown exception.");
	}
	return NULL;
}
Beispiel #4
0
BOOL bigfilehelper::GetAllVols(std::vector<VolInfo>& vVols)
{
    BOOL retval = FALSE;
    CAtlArray<TCHAR> buffer;
    TCHAR* pBuffer = NULL;
    DWORD dwSize;
    std::vector<CString> logicalDrvs;
    CString strDrv;
    POSITION pos = NULL;
    POSITION max_size_pos = NULL;
    ULONGLONG uMaxSize = 0;
    DWORD dwSectorsPerCluster;
    DWORD dwBytesPerSector;
    DWORD dwNumberOfFreeClusters;
    DWORD dwTotalNumberOfClusters;
    TCHAR szVolName[MAX_PATH+1] = { 0 };
    TCHAR szFileSystem[MAX_PATH+1] = { 0 };
    BOOL fRetCode;
    VolInfo volInfo;
    size_t idx;

    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

    buffer.SetCount(512);
    pBuffer = buffer.GetData();
    dwSize = (DWORD)buffer.GetCount();
    memset(pBuffer, 0, dwSize * sizeof(TCHAR));
    dwSize = GetLogicalDriveStrings(dwSize, buffer.GetData());

    if (dwSize > 2)
    {
        strDrv = pBuffer;
        logicalDrvs.push_back(strDrv);

        for (DWORD i = 3; i < dwSize; ++i) 
        {
            if (pBuffer[i] != 0 && pBuffer[i - 1] == 0) 
            {
                strDrv = pBuffer + i;
                logicalDrvs.push_back(strDrv);
            }
        }
    }

    for (idx = 0; idx < logicalDrvs.size(); ++idx)
    {
        CString _drv = logicalDrvs[idx];
        BOOL bRemovable = FALSE;

        if (_drv.CompareNoCase(_T("a:\\")) == 0 || 
            _drv.CompareNoCase(_T("b:\\")) == 0)
        {
            continue;
        }

        UINT uType = GetDriveType(_drv);
        if (uType != DRIVE_FIXED &&
            uType != DRIVE_REMOVABLE)
        {
            continue;
        }

        if (DRIVE_REMOVABLE == uType)
            bRemovable = TRUE;

        RtlZeroMemory(szVolName, sizeof(szVolName));
        RtlZeroMemory(szFileSystem, sizeof(szFileSystem));
        fRetCode = GetVolumeInformation(
            _drv,
            szVolName,
            MAX_PATH+1,
            NULL,
            NULL,
            NULL,
            szFileSystem,
            MAX_PATH+1
            );
        if (!fRetCode)
        {
            continue;
        }

        fRetCode = GetDiskFreeSpace(
            _drv,
            &dwSectorsPerCluster,
            &dwBytesPerSector,
            &dwNumberOfFreeClusters,
            &dwTotalNumberOfClusters
            );
        if (!fRetCode)
        {
            continue;
        }

        volInfo.cVol = (char)_drv[0];
        volInfo.strVolName = szVolName;
        if (volInfo.strVolName.IsEmpty())
            volInfo.strVolName = _T("本地磁盘");
        volInfo.qwTotalSize = (ULONGLONG)dwTotalNumberOfClusters * dwBytesPerSector * dwSectorsPerCluster;
        volInfo.qwFreeSize = (ULONGLONG)dwNumberOfFreeClusters * dwBytesPerSector * dwSectorsPerCluster;
        volInfo.bRemovable = bRemovable;
        vVols.push_back(volInfo);
    }

    retval = TRUE;

//clean0:
    return retval;
}
Beispiel #5
0
BOOL ShellCache::IsPathAllowed(LPCTSTR path)
{
	ValidatePathFilter();
	Locker lock(m_critSec);
	tristate_t allowed = pathFilter.IsPathAllowed(path);
	if (allowed != tristate_unknown)
		return allowed == tristate_true ? TRUE : FALSE;

	UINT drivetype = 0;
	int drivenumber = PathGetDriveNumber(path);
	if ((drivenumber >= 0) && (drivenumber < 25))
	{
		drivetype = drivetypecache[drivenumber];
		if ((drivetype == -1) || ((GetTickCount64() - drivetypeticker) > DRIVETYPETIMEOUT))
		{
			if ((DWORD(drivefloppy) == 0) && ((drivenumber == 0) || (drivenumber == 1)))
				drivetypecache[drivenumber] = DRIVE_REMOVABLE;
			else
			{
				drivetypeticker = GetTickCount64();
				TCHAR pathbuf[MAX_PATH + 4] = { 0 };		// MAX_PATH ok here. PathStripToRoot works with partial paths too.
				wcsncpy_s(pathbuf, path, _countof(pathbuf) - 1);
				PathStripToRoot(pathbuf);
				PathAddBackslash(pathbuf);
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": GetDriveType for %s, Drive %d\n", pathbuf, drivenumber);
				drivetype = GetDriveType(pathbuf);
				drivetypecache[drivenumber] = drivetype;
			}
		}
	}
	else
	{
		TCHAR pathbuf[MAX_PATH + 4] = { 0 };		// MAX_PATH ok here. PathIsUNCServer works with partial paths too.
		wcsncpy_s(pathbuf, path, _countof(pathbuf) - 1);
		if (PathIsUNCServer(pathbuf))
			drivetype = DRIVE_REMOTE;
		else
		{
			PathStripToRoot(pathbuf);
			PathAddBackslash(pathbuf);
			if (wcsncmp(pathbuf, drivetypepathcache, MAX_PATH - 1) == 0) // MAX_PATH ok.
				drivetype = drivetypecache[26];
			else
			{
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L"GetDriveType for %s\n", pathbuf);
				drivetype = GetDriveType(pathbuf);
				drivetypecache[26] = drivetype;
				wcsncpy_s(drivetypepathcache, pathbuf, MAX_PATH - 1); // MAX_PATH ok.
			}
		}
	}
	if ((drivetype == DRIVE_REMOVABLE) && (!IsRemovable()))
		return FALSE;
	if ((drivetype == DRIVE_FIXED) && (!IsFixed()))
		return FALSE;
	if (((drivetype == DRIVE_REMOTE) || (drivetype == DRIVE_NO_ROOT_DIR)) && (!IsRemote()))
		return FALSE;
	if ((drivetype == DRIVE_CDROM) && (!IsCDRom()))
		return FALSE;
	if ((drivetype == DRIVE_RAMDISK) && (!IsRAM()))
		return FALSE;
	if ((drivetype == DRIVE_UNKNOWN) && (IsUnknown()))
		return FALSE;

	return TRUE;
}
void LayThongTinODia(TCHAR *szODia, TCHAR *szThongTin)
{
	// Nhung bien nay dung cho ham GetVolumeInformation
	TCHAR szVolumeName[256];
	DWORD DWVolumeSerialNumber;
	DWORD DWMaximumComponentLength;
	DWORD DWFileSystemFlags;
	
	// Tat cac thong bao loi
	SetErrorMode(SEM_FAILCRITICALERRORS);

	DWErr = GetVolumeInformation(szODia, 
			szVolumeName, 256,
			&DWVolumeSerialNumber,
			&DWMaximumComponentLength,
			&DWFileSystemFlags,
			NULL, 0);
	if (DWErr == 0)
	{
		if (GetLastError() == 21) // Loi khong co dia trong o dia mem hoac CD-ROM
		{
			UINT t = GetDriveType(szODia);
			switch (t)
			{
			case DRIVE_CDROM:
				wcscpy_s(szVolumeName, _T("CD-ROM Drive"));
				break;
			case DRIVE_REMOVABLE:
				wcscpy_s(szVolumeName, _T("Floppy Drive"));
				break;
			}
		}
		else
			ErrorExit(_T("\"GetVolumeInformation\""));		
	}

	// Truong hop o dia khong co ten
	if (_tcslen(szVolumeName) == 0)
	{
		UINT t = GetDriveType(szODia);
		switch (t)
		{
		case DRIVE_CDROM:
			wcscpy_s(szVolumeName, _T("CD-ROM Drive"));
			break;
		case DRIVE_REMOVABLE:
			wcscpy_s(szVolumeName, _T("Removable Hard Disk"));
			break;
		case DRIVE_RAMDISK:
			wcscpy_s(szVolumeName, _T("RAM Disk"));
			break;
		case DRIVE_FIXED:
			wcscpy_s(szVolumeName, _T("Local Disk"));
			break;
		}
	}

	szODia[2] = '\0';
	wsprintf(szThongTin, _T("%s (%s)"), szVolumeName, szODia); 
	szODia[2] = '\\';

	// Bat lai cac thong bao loi
	SetErrorMode(0);
}
Beispiel #7
0
/*
** Read the options specified in the ini file.
**
*/
void MeasureDiskSpace::ReadOptions(ConfigParser& parser, const WCHAR* section)
{
	double oldMaxValue = m_MaxValue;

	Measure::ReadOptions(parser, section);

	m_Drive = parser.ReadString(section, L"Drive", L"C:\\");
	if (m_Drive.empty())
	{
		LogWarningF(this, L"FreeDiskSpace: Drive= empty");
		m_Value = 0.0;
		m_MaxValue = 0.0;
		m_OldTotalBytes = 0;
		m_StringValue.clear();
	}
	else
	{
		// A trailing backslash is required for GetDiskFreeSpaceEx().
		PathUtil::AppendBacklashIfMissing(m_Drive);
	}

	m_Type = (1 == parser.ReadInt(section, L"Type", 0));
	m_Total = (1 == parser.ReadInt(section, L"Total", 0));
	m_Label = (1 == parser.ReadInt(section, L"Label", 0));
	m_IgnoreRemovable = (1 == parser.ReadInt(section, L"IgnoreRemovable", 1));
	m_DiskQuota = (1 == parser.ReadInt(section, L"DiskQuota", 1));
	
	// Set the m_MaxValue
	if (!m_Initialized)
	{
		BOOL result = FALSE;
		ULONGLONG i64TotalBytes;

		if (!m_Drive.empty())
		{
			const WCHAR* drive = m_Drive.c_str();
			UINT type = GetDriveType(drive);
			if (type != DRIVE_NO_ROOT_DIR &&
				type != DRIVE_CDROM &&
				(!m_IgnoreRemovable || type != DRIVE_REMOVABLE))  // Ignore CD-ROMS and removable drives
			{
				result = GetDiskFreeSpaceEx(drive, nullptr, (PULARGE_INTEGER)&i64TotalBytes, nullptr);
			}
		}

		if (result)
		{
			m_MaxValue = (double)(__int64)i64TotalBytes;
			m_OldTotalBytes = i64TotalBytes;
		}
		else
		{
			m_MaxValue = 0.0;
			m_OldTotalBytes = 0;
		}
	}
	else
	{
		if (m_Type)
		{
			m_MaxValue = DRIVETYPE_MAX;
			m_OldTotalBytes = 0;
		}
		else
		{
			m_MaxValue = oldMaxValue;
		}
	}
}
Beispiel #8
0
// takes a root drive path, returns true if it is a cdrom drive
bool is_cdrom(const char drive[])
{
	return (DRIVE_CDROM == GetDriveType(drive));
}
int _tmain(int argc, _TCHAR* argv[])
{
	_tprintf ( _T(" Vireio DLL link Install/Uninstall Utility\r\n"));
	_tprintf ( _T(" -------------------------------------\r\n"));
	_tprintf ( _T("\r\n"));
	_tprintf ( _T("NOTE: THIS TOOL IS ONLY REQUIRED IF VIREIO DOES NOT INJECT WITH THE\r\n"));
	_tprintf ( _T("PERCEPTION APP RUNNING WHEN YOU START THE GAME\r\n"));
	_tprintf ( _T("\r\n"));
	std::string instructions;
	instructions += "This will create symbolic links to the Vireio DLLs in the target\r\n";
	instructions += "folder rather than physically copying them.\r\n";
	instructions += "To uninstall the symbolic links just run this application again\r\n";
	instructions += "and select the game folder and the symbolic links will be removed\r\n";
	instructions += "This means if you upgrade Vireio and put it in the same location as the\r\n";
	instructions += "previous version there is no need to re-run this installation tool\r\n";
	instructions += "This application needs to run as Administrator to create symlinks\r\n";
	instructions += "\r\n";
	instructions += "** Please select target game root folder in selection dialog **\r\n";
	_tprintf ( instructions.c_str());

	std::string rootFolder = GetLastPath();
	if (rootFolder.length() == 0)
	{
		std::string localDriveList;
		DWORD dw = GetLogicalDrives();
		char d[] = {'A', 0};
		while (dw)
		{
			if (dw & 1)
			{
				std::string drive = std::string(d) + ":\\";
				if (GetDriveType(drive.c_str()) == DRIVE_FIXED)
					localDriveList += d;
			}
			dw = dw >> 1;
			d[0]++;
		}

		std::vector<std::string> steamLocations;
		steamLocations.push_back(":\\Program Files (x86)\\Steam\\SteamApps\\common");
		steamLocations.push_back(":\\Program Files\\Steam\\SteamApps\\common");
		steamLocations.push_back(":\\Steam\\SteamApps\\common");

		bool foundPath = false;
		std::string steamLocation;
		for (int i = 0; (i < localDriveList.length() && !foundPath); i++)
		{
			//Attempt to find the right root folder
			int location = 0;
			while (location < (int)steamLocations.size())
			{
				std::string path = localDriveList[i] + steamLocations[location];
				if (PathFileExists(path.c_str()))
				{
					foundPath = true;
					steamLocation = path;
					break;
				}
				location++;
			}
		}

		if (!foundPath)
		{
			//Fail, just go to user's documents folder
			PWSTR pszPath = NULL;
			SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &pszPath);
			char path[1024];
			size_t c  = 0;
			wcstombs_s(&c, path, pszPath, 1024);
			rootFolder = path;
		}
		else
			rootFolder =  steamLocation;
	}
Beispiel #10
0
bool CSysInfo::GetDiskSpace(const std::string& drive,int& iTotal, int& iTotalFree, int& iTotalUsed, int& iPercentFree, int& iPercentUsed)
{
  bool bRet= false;
  ULARGE_INTEGER ULTotal= { { 0 } };
  ULARGE_INTEGER ULTotalFree= { { 0 } };

  if( !drive.empty() && drive != "*" )
  {
#ifdef TARGET_WINDOWS
    UINT uidriveType = GetDriveType(( drive + ":\\" ).c_str());
    if(uidriveType != DRIVE_UNKNOWN && uidriveType != DRIVE_NO_ROOT_DIR)
      bRet= ( 0 != GetDiskFreeSpaceEx( ( drive + ":\\" ).c_str(), NULL, &ULTotal, &ULTotalFree) );
#elif defined(TARGET_POSIX)
    bRet = (0 != GetDiskFreeSpaceEx(drive.c_str(), NULL, &ULTotal, &ULTotalFree));
#endif
  }
  else
  {
    ULARGE_INTEGER ULTotalTmp= { { 0 } };
    ULARGE_INTEGER ULTotalFreeTmp= { { 0 } };
#ifdef TARGET_WINDOWS
    char* pcBuffer= NULL;
    DWORD dwStrLength= GetLogicalDriveStrings( 0, pcBuffer );
    if( dwStrLength != 0 )
    {
      dwStrLength+= 1;
      pcBuffer= new char [dwStrLength];
      GetLogicalDriveStrings( dwStrLength, pcBuffer );
      int iPos= 0;
      do {
        if( DRIVE_FIXED == GetDriveType( pcBuffer + iPos  ) &&
            GetDiskFreeSpaceEx( ( pcBuffer + iPos ), NULL, &ULTotal, &ULTotalFree ) )
        {
          ULTotalTmp.QuadPart+= ULTotal.QuadPart;
          ULTotalFreeTmp.QuadPart+= ULTotalFree.QuadPart;
        }
        iPos += (strlen( pcBuffer + iPos) + 1 );
      }while( strlen( pcBuffer + iPos ) > 0 );
    }
    delete[] pcBuffer;
#else // for linux and osx
    if( GetDiskFreeSpaceEx( "/", NULL, &ULTotal, &ULTotalFree ) )
    {
      ULTotalTmp.QuadPart+= ULTotal.QuadPart;
      ULTotalFreeTmp.QuadPart+= ULTotalFree.QuadPart;
    }
#endif
    if( ULTotalTmp.QuadPart || ULTotalFreeTmp.QuadPart )
    {
      ULTotal.QuadPart= ULTotalTmp.QuadPart;
      ULTotalFree.QuadPart= ULTotalFreeTmp.QuadPart;
      bRet= true;
    }
  }

  if( bRet )
  {
    iTotal = (int)( ULTotal.QuadPart / MB );
    iTotalFree = (int)( ULTotalFree.QuadPart / MB );
    iTotalUsed = iTotal - iTotalFree;
    if( ULTotal.QuadPart > 0 )
    {
      iPercentUsed = (int)( 100.0f * ( ULTotal.QuadPart - ULTotalFree.QuadPart ) / ULTotal.QuadPart + 0.5f );
    }
    else
    {
      iPercentUsed = 0;
    }
    iPercentFree = 100 - iPercentUsed;
  }

  return bRet;
}
Beispiel #11
0
int
nt_get_filename_info(const char *pszPath, char *pszFull, size_t cchFull)
{
    static char                     abBuf[8192];
    PMY_FILE_NAME_INFORMATION       pFileNameInfo = (PMY_FILE_NAME_INFORMATION)abBuf;
    PMY_FILE_FS_VOLUME_INFORMATION  pFsVolInfo = (PMY_FILE_FS_VOLUME_INFORMATION)abBuf;
    MY_IO_STATUS_BLOCK              Ios;
    LONG                            rcNt;
    HANDLE                      hFile;
    int                             cchOut;
    char                           *psz;
    int                             iDrv;
    int                             rc;

    /*
     * Check for NtQueryInformationFile the first time around.
     */
    if (!g_fInitialized)
    {
        g_fInitialized = TRUE;
        if (!getenv("KMK_DONT_USE_NT_QUERY_INFORMATION_FILE"))
        {
            *(FARPROC *)&g_pfnNtQueryInformationFile =
                GetProcAddress(LoadLibrary("ntdll.dll"), "NtQueryInformationFile");
            *(FARPROC *)&g_pfnNtQueryVolumeInformationFile =
                GetProcAddress(LoadLibrary("ntdll.dll"), "NtQueryVolumeInformationFile");
        }
        if (    g_pfnNtQueryInformationFile
            &&  g_pfnNtQueryVolumeInformationFile)
        {
            unsigned i;
            for (i = 0; i < sizeof(g_afNtfsDrives) / sizeof(g_afNtfsDrives[0]); i++ )
                g_afNtfsDrives[i] = -1;
        }
        else
        {
            g_pfnNtQueryVolumeInformationFile = NULL;
            g_pfnNtQueryInformationFile = NULL;
        }
    }
    if (!g_pfnNtQueryInformationFile)
        return -1;

    /*
     * The FileNameInformation we get is relative to where the volume is mounted,
     * so we have to extract the driveletter prefix ourselves.
     *
     * FIXME: This will probably not work for volumes mounted in NTFS sub-directories.
     */
    psz = pszFull;
    if (pszPath[0] == '\\' || pszPath[0] == '/')
    {
        /* unc or root of volume */
        if (    (pszPath[1] == '\\' || pszPath[1] == '/')
            &&  (pszPath[2] != '\\' || pszPath[2] == '/'))
        {
#if 0 /* don't bother with unc yet. */
            /* unc - we get the server + name back */
            *psz++ = '\\';
#endif
            return -1;
        }
        /* root slash */
        *psz++ = _getdrive() + 'A' - 1;
        *psz++ = ':';
    }
    else if (pszPath[1] == ':' && isalpha(pszPath[0]))
    {
        /* drive letter */
        *psz++ = toupper(pszPath[0]);
        *psz++ = ':';
    }
    else
    {
        /* relative */
        *psz++ = _getdrive() + 'A' - 1;
        *psz++ = ':';
    }
    iDrv = *pszFull - 'A';

    /*
     * Fat32 doesn't return filenames with the correct case, so restrict it
     * to NTFS volumes for now.
     */
    if (g_afNtfsDrives[iDrv] == -1)
    {
        /* FSCTL_GET_REPARSE_POINT? Enumerate mount points? */
        g_afNtfsDrives[iDrv] = 0;
        psz[0] = '\\';
        psz[1] = '\0';
#if 1
        hFile = CreateFile(pszFull,
                           GENERIC_READ,
                           FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                           NULL,
                           OPEN_EXISTING,
                           FILE_FLAG_BACKUP_SEMANTICS,
                           NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            PMY_FILE_FS_ATTRIBUTE_INFORMATION pFsAttrInfo = (PMY_FILE_FS_ATTRIBUTE_INFORMATION)abBuf;

            memset(&Ios, 0, sizeof(Ios));
            rcNt = g_pfnNtQueryVolumeInformationFile(hFile, &Ios, abBuf, sizeof(abBuf),
                                                     MY_FileFsAttributeInformation);
            if (    rcNt >= 0
                //&&  pFsAttrInfo->FileSystemNameLength == 4
                &&  pFsAttrInfo->FileSystemName[0] == 'N'
                &&  pFsAttrInfo->FileSystemName[1] == 'T'
                &&  pFsAttrInfo->FileSystemName[2] == 'F'
                &&  pFsAttrInfo->FileSystemName[3] == 'S'
                &&  pFsAttrInfo->FileSystemName[4] == '\0')
            {
                memset(&Ios, 0, sizeof(Ios));
                rcNt = g_pfnNtQueryVolumeInformationFile(hFile, &Ios, &g_aVolumeInfo[iDrv],
                                                         sizeof(MY_FILE_FS_VOLUME_INFORMATION),
                                                         MY_FileFsVolumeInformation);
                if (rcNt >= 0)
                {
                    DWORD dwDriveType = GetDriveType(pszFull);
                    if (    dwDriveType == DRIVE_FIXED
                        ||  dwDriveType == DRIVE_RAMDISK)
                        g_afNtfsDrives[iDrv] = 1;
                }
            }
            CloseHandle(hFile);
        }
#else
        {
            char szFSName[32];
            if (    GetVolumeInformation(pszFull,
                                         NULL, 0,   /* volume name */
                                         NULL,      /* serial number */
                                         NULL,      /* max component */
                                         NULL,      /* volume attribs */
                                         szFSName,
                                         sizeof(szFSName))
                &&  !strcmp(szFSName, "NTFS"))
            {
                g_afNtfsDrives[iDrv] = 1;
            }
        }
#endif
    }
    if (!g_afNtfsDrives[iDrv])
        return -1;

    /*
     * Try open the path and query its file name information.
     */
    hFile = CreateFile(pszPath,
                       GENERIC_READ,
                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                       NULL,
                       OPEN_EXISTING,
                       FILE_FLAG_BACKUP_SEMANTICS,
                       NULL);
    if (hFile != INVALID_HANDLE_VALUE)
    {
        /* check that the driver letter is correct first (reparse / symlink issues). */
        memset(&Ios, 0, sizeof(Ios));
        rcNt = g_pfnNtQueryVolumeInformationFile(hFile, &Ios, pFsVolInfo, sizeof(*pFsVolInfo), MY_FileFsVolumeInformation);
        if (rcNt >= 0)
        {
            /** @todo do a quick search and try correct the drive letter? */
            if (    pFsVolInfo->VolumeCreationTime.QuadPart == g_aVolumeInfo[iDrv].VolumeCreationTime.QuadPart
                &&  pFsVolInfo->VolumeSerialNumber == g_aVolumeInfo[iDrv].VolumeSerialNumber)
            {
                memset(&Ios, 0, sizeof(Ios));
                rcNt = g_pfnNtQueryInformationFile(hFile, &Ios, abBuf, sizeof(abBuf), MY_FileNameInformation);
                if (rcNt >= 0)
                {
                    cchOut = WideCharToMultiByte(CP_ACP, 0,
                                                 pFileNameInfo->FileName, pFileNameInfo->FileNameLength / sizeof(WCHAR),
                                                 psz, (int)(cchFull - (psz - pszFull) - 2), NULL, NULL);
                    if (cchOut > 0)
                    {
                        const char *pszEnd;
#if 0
                        /* upper case the server and share */
                        if (fUnc)
                        {
                            for (psz++; *psz != '/' && *psz != '\\'; psz++)
                                *psz = toupper(*psz);
                            for (psz++; *psz != '/' && *psz != '\\'; psz++)
                                *psz = toupper(*psz);
                        }
#endif
                        /* add trailing slash on directories if input has it. */
                        pszEnd = strchr(pszPath, '\0');
                        if (    (pszEnd[-1] == '/' || pszEnd[-1] == '\\')
                            &&  psz[cchOut - 1] != '\\'
                            &&  psz[cchOut - 1] != '//')
                            psz[cchOut++] = '\\';

                        /* make sure it's terminated */
                        psz[cchOut] = '\0';
                        rc = 0;
                    }
                    else
                        rc = -3;
                }
                else
                    rc = -4;
            }
            else
                rc = -5;
        }
        else
            rc = -6;
        CloseHandle(hFile);
    }
    else
        rc = -7;
    return rc;
}
Beispiel #12
0
static BOOL
eject_drive_letter(WCHAR DriveLetter) {
    LPWSTR szRootPath = L"X:\\", 
           szDevicePath = L"X:", 
           szVolumeAccessPath = L"\\\\.\\X:";
    WCHAR  szDosDeviceName[MAX_PATH];
    long DeviceNumber, res, tries;
    HANDLE hVolume; 
    STORAGE_DEVICE_NUMBER sdn;
    DWORD dwBytesReturned;
    DEVINST DevInst;
    ULONG Status;
    ULONG ProblemNumber;
    UINT DriveType;
    PNP_VETO_TYPE VetoType;
    WCHAR VetoNameW[MAX_PATH];
    BOOL bSuccess;
    DEVINST DevInstParent;
    
    szRootPath[0] = DriveLetter;
    szDevicePath[0] = DriveLetter;
    szVolumeAccessPath[4] = DriveLetter;

    DeviceNumber = -1;

    hVolume = CreateFile(szVolumeAccessPath, 0,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        NULL, OPEN_EXISTING, 0, NULL);
    if (hVolume == INVALID_HANDLE_VALUE) {
        PyErr_SetString(PyExc_ValueError, "Invalid handle value for drive letter");
        return FALSE;
    }

    dwBytesReturned = 0;
    res = DeviceIoControl(hVolume,
                        IOCTL_STORAGE_GET_DEVICE_NUMBER,
                        NULL, 0, &sdn, sizeof(sdn),
                        &dwBytesReturned, NULL);
    if ( res ) {
        DeviceNumber = sdn.DeviceNumber;
    }
    CloseHandle(hVolume);

    if ( DeviceNumber == -1 ) {
        PyErr_SetString(PyExc_ValueError, "Can't find drive number");
        return FALSE;
    }

    res = QueryDosDevice(szDevicePath, szDosDeviceName, MAX_PATH);
    if ( !res ) {
       PyErr_SetString(PyExc_ValueError, "Can't find dos device");
       return FALSE;
    }

    DriveType = GetDriveType(szRootPath);

    DevInst = GetDrivesDevInstByDeviceNumber(DeviceNumber,
                  DriveType, szDosDeviceName);
    if (DevInst == 0) return FALSE;

    DevInstParent = 0;
    Status = 0;
    ProblemNumber = 0;
    bSuccess = FALSE;

    res = CM_Get_Parent(&DevInstParent, DevInst, 0);

    for ( tries = 0; tries < 3; tries++ ) {
        VetoNameW[0] = 0;

        res = CM_Request_Device_EjectW(DevInstParent,
                &VetoType, VetoNameW, MAX_PATH, 0);

        bSuccess = (res==CR_SUCCESS &&
                            VetoType==PNP_VetoTypeUnknown);
        if ( bSuccess )  {
            break;
        }

        Sleep(500); // required to give the next tries a chance!
    }
    if (!bSuccess)  PyErr_SetString(PyExc_ValueError, "Failed to eject drive after three tries");
    return bSuccess;
}
Beispiel #13
0
BOOL
get_all_removable_disks(struct tagDrives *g_drives)
{
    WCHAR	caDrive[4];
	WCHAR	volume[BUFSIZE];
	int		nLoopIndex;
	DWORD	dwDriveMask;
	unsigned int g_count=0;


	caDrive[0]	= 'A';
    caDrive[1]	= ':';
    caDrive[2]	= '\\';
    caDrive[3]	= 0;





	// Get all drives in the system.
    dwDriveMask = GetLogicalDrives();


	if(dwDriveMask == 0)
	{
		PyErr_SetString(DriveError, "GetLogicalDrives failed");
		return FALSE;
	}


	// Loop for all drives (MAX_DRIVES = 26)


    for(nLoopIndex = 0; nLoopIndex < MAX_DRIVES; nLoopIndex++)
    {
        // if a drive is present (we cannot ignore the A and B drives as there
        // are people out there that think mapping devices to use those letters
        // is a good idea, sigh)
		if(dwDriveMask & 1)
        {
            caDrive[0] = 'A' + nLoopIndex;


			// If a drive is removable
			if(GetDriveType(caDrive) == DRIVE_REMOVABLE)
			{
				//Get its volume info and store it in the global variable.
				if(GetVolumeNameForVolumeMountPoint(caDrive, volume, BUFSIZE))
	            {
		            g_drives[g_count].letter = caDrive[0];
					wcscpy_s(g_drives[g_count].volume, BUFSIZE, volume);
					g_count ++;
				}

			}
		}
		dwDriveMask >>= 1;
	}


	// success if atleast one removable drive is found.
	if(g_count == 0)
	{
	    PyErr_SetString(DriveError, "No removable drives found");
		return FALSE;
	}
	return TRUE;

}
bool GetSystemInfo(SYSTEMINIT& sysinfo)
{
	/////get computer name///////
	TCHAR computerbuf[256];
	DWORD computersize=256;
	memset(computerbuf,0,256);
	if(!GetComputerName(computerbuf,&computersize))
		return false;
	computerbuf[computersize]=0;
	sysinfo.computer[0]=0;
	strcat(sysinfo.computer,"计算机: ");
	strcat(sysinfo.computer,computerbuf);
	///////get user name/////////
	TCHAR userbuf[256];
	DWORD usersize=256;
	memset(userbuf,0,256);
	if(!GetUserName(userbuf,&usersize))
		return false;
	userbuf[usersize]=0;
	sysinfo.user[0]=0;
	strcat(sysinfo.user,"用户名: ");
	strcat(sysinfo.user,userbuf);
	///////get version//////////
	sysinfo.os[0]=0;
	strcat(sysinfo.os,"操作系统: ");
	OSVERSIONINFO osvi;
	memset(&osvi,0,sizeof(osvi));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	if(!GetVersionEx(&osvi))
		return false;
	switch (osvi.dwPlatformId)
	{
      case VER_PLATFORM_WIN32_NT:
          if ( osvi.dwMajorVersion <= 4 )
			 strcat(sysinfo.os,"Microsoft Windows NT ");
         if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
			 strcat(sysinfo.os,"Microsoft Windows 2000 ");
         HKEY hKey;
         char szProductType[80];
         DWORD dwBufLen;
         RegOpenKeyEx( HKEY_LOCAL_MACHINE,
               "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
               0, KEY_QUERY_VALUE, &hKey );
         RegQueryValueEx( hKey, "ProductType", NULL, NULL,
               (LPBYTE)szProductType, &dwBufLen);
         RegCloseKey(hKey);
         if ( lstrcmpi( "WINNT", szProductType) == 0 )
			 strcat(sysinfo.os,"Professional, " );
         if ( lstrcmpi( "LANMANNT", szProductType) == 0 )
             strcat(sysinfo.os,"Server, " );
         if ( lstrcmpi( "SERVERNT", szProductType) == 0 )
             strcat(sysinfo.os,"Advanced Server, " );
         if ( osvi.dwMajorVersion <= 4 )
         {
			 char temp[256];
			 sprintf(temp,"version %d.%d %s (Build %d)\n",
               osvi.dwMajorVersion,
               osvi.dwMinorVersion,
               osvi.szCSDVersion,
               osvi.dwBuildNumber & 0xFFFF);
			 strcat(sysinfo.os,temp);
         }
         else
         { 
			 char temp[256];
             sprintf(temp,"%s (Build %d)\n",
               osvi.szCSDVersion,
               osvi.dwBuildNumber & 0xFFFF);
			 strcat(sysinfo.os,temp);
         }
         break;
      case VER_PLATFORM_WIN32_WINDOWS:
         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
         {
             strcat(sysinfo.os,"Microsoft Windows 95 ");
             if ( osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B' )
                strcat(sysinfo.os,"OSR2 " );
         } 

         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
         {
             strcat(sysinfo.os,"Microsoft Windows 98 ");
             if ( osvi.szCSDVersion[1] == 'A' )
                strcat(sysinfo.os,"SE " );
         } 

         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
         {
             strcat(sysinfo.os,"Microsoft Windows Millennium Edition ");
         } 
         break;
    }
	///////////get disk space/////////////
	sysinfo.disk[0]=0;
	strcat(sysinfo.disk,"磁盘空间: ");
	DWORD maskdriver;
	ULONGLONG totalspace=0,freespace=0;
	ULONGLONG ulltotalspace,ullfreespace,freebyte;
	DWORD drivertype;
	char driver[10];
	if(!(maskdriver=GetLogicalDrives()))
		return false;
	for(int i=0;i<26;i++)
	{
		if(!(maskdriver>>i))
			break;
		if(maskdriver>>i&1)
		{
			driver[0]=i+'A';
			driver[1]=':';
			driver[2]='\\';
			driver[3]=0;
			drivertype=GetDriveType(driver);
			if(drivertype!=DRIVE_FIXED)
				continue;
			if(!GetDiskFreeSpaceEx (driver,
							(PULARGE_INTEGER)&freebyte,
							(PULARGE_INTEGER)&ulltotalspace,
							(PULARGE_INTEGER)&ullfreespace))
							return false;
			totalspace+=ulltotalspace;
			freespace+=ullfreespace;
		}
	}
	signed __int64 dfreespace=0.0,dtotalspace=0.0,lv;
	dfreespace=(signed __int64)freespace/(1024*1024*1024);
	dtotalspace=(signed __int64)totalspace/(1024*1024*1024);
	lv=(signed __int64)freespace/totalspace*100;
	char space[256];
	sprintf(space,"总磁盘空间为:%.2fG,剩余磁盘空间为:%.2fG(占%.2f%c)",dtotalspace,dfreespace,lv,'%');
	strcat(sysinfo.disk,space);
	////////////////get cpu info//////////////////
	sysinfo.processor[0]=0;
	strcat(sysinfo.processor,"CPU: ");
	HKEY hKey;
	char szcpuinfo[80];
	DWORD dwBufLen=80;
	RegOpenKeyEx( HKEY_LOCAL_MACHINE,
	   "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
	   0, KEY_QUERY_VALUE, &hKey );
	RegQueryValueEx( hKey, "VendorIdentifier", NULL, NULL,
	   (LPBYTE)szcpuinfo, &dwBufLen);
	szcpuinfo[dwBufLen]=0;
	strcat(sysinfo.processor,szcpuinfo);
	strcat(sysinfo.processor," ");
	memset(szcpuinfo,0,80);
	dwBufLen=80;
	RegQueryValueEx( hKey, "Identifier", NULL, NULL,
	   (LPBYTE)szcpuinfo, &dwBufLen);
	szcpuinfo[dwBufLen]=0;
	strcat(sysinfo.processor,szcpuinfo);
	DWORD f;
	dwBufLen=8;
	RegQueryValueEx( hKey, "~MHz", NULL, NULL,
	   (LPBYTE)&f, &dwBufLen);
	char hz[10];
	sprintf(hz," %dMHZ",f);
	strcat(sysinfo.processor,hz);
	RegCloseKey(hKey);
	/////////////get mem size////////////
	MEMORYSTATUS ms;
	GlobalMemoryStatus(&ms);
	char membuf[256];
	sprintf(membuf,"物理内存: 总物理内存:%dMB,可用内存:%dMB (占%.2f%s)",ms.dwTotalPhys/1024/1024,ms.dwAvailPhys/1024/1024
		,(double)ms.dwAvailPhys/ms.dwTotalPhys*100,"%");
	sysinfo.mem[0]=0;
	strcpy(sysinfo.mem,membuf);
	return true; 
}
Beispiel #15
0
int fileselector(char *name, char *path, char *filter, char *title, int filemode)
{
  int c, d, scrrep;
  int color;
  int files;
  int filepos = 0;
  int fileview = 0;
  int lastclick = 0;
  int lastfile = 0;
  int lowest;
  int exitfilesel;

  DIR *dir;
  struct dirent *de;
  struct stat st;
  #ifdef __WIN32__
  char drivestr[] = "A:\\";
  char driveexists[26];
  #endif
  char cmpbuf[MAX_PATHNAME];
  char tempname[MAX_PATHNAME];

  // Set initial path (if any)
  if (strlen(path)) chdir(path);

  // Scan for all existing drives
  #ifdef __WIN32__
  for (c = 0; c < 26; c++)
  {
    drivestr[0] = 'A'+c;
    if (GetDriveType(drivestr) > 1) driveexists[c] = 1;
    else driveexists[c] = 0;
  }
  #endif

  // Read new directory
  NEWPATH:
  getcwd(path, MAX_PATHNAME);
  files = 0;
  // Deallocate old names
  for (c = 0; c < MAX_DIRFILES; c++)
  {
    if (direntry[c].name)
    {
      free(direntry[c].name);
      direntry[c].name = NULL;
    }
  }
  #ifdef __WIN32__
  // Create drive letters
  for (c = 0; c < 26; c++)
  {
    if (driveexists[c])
    {
      drivestr[0] = 'A'+c;
      direntry[files].name = strdup(drivestr);
      direntry[files].attribute = 2;
      files++;
    }
  }
  #endif

  // Process directory
  #ifdef __amigaos__
  dir = opendir("");
  #else
  dir = opendir(".");
  #endif
  if (dir)
  {
    char *filtptr = strstr(filter, "*");
    if (!filtptr) filtptr = filter;
    else filtptr++;
    for (c = 0; c < strlen(filter); c++)
      filter[c] = tolower(filter[c]);

    while ((de = readdir(dir)))
    {
      if ((files < MAX_DIRFILES) && (strlen(de->d_name) < MAX_FILENAME))
      {
        direntry[files].name = strdup(de->d_name);
        direntry[files].attribute = 0;
        stat(de->d_name, &st);
        if (st.st_mode & S_IFDIR)
        {
          direntry[files].attribute = 1;
          files++;
        }
        else
        {
          int c;
          // If a file, must match filter
          strcpy(cmpbuf, de->d_name);
          if ((!strcmp(filtptr, "*")) || (!strcmp(filtptr, ".*")))
            files++;
          else
          {
            for (c = 0; c < strlen(cmpbuf); c++)
              cmpbuf[c] = tolower(cmpbuf[c]);
            if (strstr(cmpbuf, filtptr))
              files++;
            else
            {
              free(direntry[files].name);
              direntry[files].name = NULL;
            }
          }
        }
      }
    }
    closedir(dir);
  }
  // Sort the filelist in a most horrible fashion
  for (c = 0; c < files; c++)
  {
    lowest = c;
    for (d = c+1; d < files; d++)
    {
      if (direntry[d].attribute < direntry[lowest].attribute)
      {
        lowest = d;
      }
      else
      {
        if (direntry[d].attribute == direntry[lowest].attribute)
        {
          if (cmpname(direntry[d].name, direntry[lowest].name) < 0)
          {
            lowest = d;
          }
        }
      }
    }
    if (lowest != c)
    {
      DIRENTRY swaptemp = direntry[c];
      direntry[c] = direntry[lowest];
      direntry[lowest] = swaptemp;
    }
  }

  // Search for the current filename
  fileview = 0;
  filepos = 0;
  for (c = 0; c < files; c++)
  {
    if ((!direntry[c].attribute) && (!cmpname(name, direntry[c].name)))
    {
      filepos = c;
    }
  }

  exitfilesel = -1;
  while (exitfilesel < 0)
  {
    int cc = cursorcolortable[cursorflash];
    if (cursorflashdelay >= 6)
    {
      cursorflashdelay %= 6;
      cursorflash++;
      cursorflash &= 3;
    }
    fliptoscreen();
    getkey();
    if (lastclick) lastclick--;

    if (win_quitted)
    {
      exitprogram = 1;
      for (c = 0; c < MAX_DIRFILES; c++)
      {
        if (direntry[c].name)
        {
          free(direntry[c].name);
          direntry[c].name = NULL;
        }
      }
      return 0;
    }

    if (mouseb)
    {
      // Cancel (click outside)
      if ((mousey < 3) || (mousey > 3+VISIBLEFILES+6) || (mousex <= 4+10) || (mousex >= 75+10))
      {
        if ((!prevmouseb) && (lastclick)) exitfilesel = 0;
      }

      // Select dir,name,filter
      if ((mousey >= 3+VISIBLEFILES+3) && (mousey <= 3+VISIBLEFILES+5) && (mousex >= 14+10) && (mousex <= 73+10))
      {
        filemode = mousey - (3+VISIBLEFILES+3) + 1;
        if ((filemode == 3) && (!prevmouseb) && (lastclick)) goto ENTERFILE;
      }

      // Select file from list
      if ((mousey >= 3) && (mousey <= 3+VISIBLEFILES+2) && (mousex >= 6+10) && (mousex <= 73+10))
      {
        filemode = 0;
        filepos = mousey - 4 - 1 + fileview;
        if (filepos < 0) filepos = 0;
        if (filepos > files-1) filepos = files - 1;

        if (!direntry[filepos].attribute)
          strcpy(name, direntry[filepos].name);

        if ((!prevmouseb) && (lastclick) && (lastfile == filepos)) goto ENTERFILE;
      }
    }

    if (!filemode)
    {
      if (((key >= '0') && (key <= '0')) || ((key >= 'a') && (key <= 'z')) || ((key >= 'A') && (key <= 'Z')))
      {
        char k = tolower(key);
        int oldfilepos = filepos;

        for (filepos = oldfilepos + 1; filepos < files; filepos++)
          if (tolower(direntry[filepos].name[0]) == k) break;
        if (filepos >= files)
        {
          for (filepos = 0; filepos < oldfilepos; filepos++)
             if (tolower(direntry[filepos].name[0]) == k) break;
        }

        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
    }

    switch(rawkey)
    {
      case KEY_ESC:
      exitfilesel = 0;
      break;

      case KEY_BACKSPACE:
      if (!filemode)
      {
      #ifdef __amigaos__
        chdir("/");
      #else
        chdir("..");
      #endif
        goto NEWPATH;
      }
      break;

      case KEY_HOME:
      if (!filemode)
      {
        filepos = 0;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_END:
      if (!filemode)
      {
        filepos = files-1;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_PGUP:
      for (scrrep = PGUPDNREPEAT; scrrep; scrrep--)
      {
        if ((!filemode) && (filepos > 0))
        {
          filepos--;
          if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
        }
      }
      break;

      case KEY_UP:
      if ((!filemode) && (filepos > 0))
      {
        filepos--;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_PGDN:
      for (scrrep = PGUPDNREPEAT; scrrep; scrrep--)
      {
        if ((!filemode) && (filepos < files-1))
        {
          filepos++;
          if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
        }
      }
      break;

      case KEY_DOWN:
      if ((!filemode) && (filepos < files-1))
      {
        filepos++;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_TAB:
      if (!shiftpressed)
      {
        filemode++;
        if (filemode > 3) filemode = 0;
      }
      else
      {
        filemode--;
        if (filemode < 0) filemode = 3;
      }
      break;

      case KEY_ENTER:
      ENTERFILE:
      switch(filemode)
      {
        case 0:
        switch (direntry[filepos].attribute)
        {
          case 0:
          strcpy(name, direntry[filepos].name);
          exitfilesel = 1;
          break;

          case 1:
          chdir(direntry[filepos].name);
          goto NEWPATH;

          case 2:
          strcpy(tempname, direntry[filepos].name);
          if (strlen(tempname))
          {
            if (tempname[strlen(tempname)-1] != '\\')
              strcat(tempname, "\\");
          }
          chdir(tempname);
          goto NEWPATH;
        }
        break;

        case 1:
        chdir(path);
        case 2:
        filemode = 0;
        goto NEWPATH;

        case 3:
        exitfilesel = 1;
        break;
      }
      break;
    }

    switch(filemode)
    {
      case 1:
      editstring(path, MAX_PATHNAME);
      break;

      case 2:
      editstring(filter, MAX_FILENAME);
      break;

      case 3:
      editstring(name, MAX_FILENAME);
      break;
    }

    // Validate filelist view
    if (filepos < fileview) fileview = filepos;
    if (filepos - fileview >= VISIBLEFILES) fileview = filepos - VISIBLEFILES + 1;

    // Refresh fileselector display
    if (isplaying()) printstatus();
    for (c = 0; c < VISIBLEFILES+7; c++)
    {
      printblank(50-(MAX_FILENAME+10)/2, 3+c, MAX_FILENAME+10);
    }
    drawbox(50-(MAX_FILENAME+10)/2, 3, 15, MAX_FILENAME+10, VISIBLEFILES+7);
    printblankc(50-(MAX_FILENAME+10)/2+1, 4, 15+16,MAX_FILENAME+8);
    printtext(50-(MAX_FILENAME+10)/2+1, 4, 15+16, title);

    for (c = 0; c < VISIBLEFILES; c++)
    {
      if ((fileview+c >= 0) && (fileview+c < files))
      {
        switch (direntry[fileview+c].attribute)
        {
          case 0:
          sprintf(textbuffer, "%-60s        ", direntry[fileview+c].name);
          break;

          case 1:
          sprintf(textbuffer, "%-60s   <DIR>", direntry[fileview+c].name);
          break;

          case 2:
          sprintf(textbuffer, "%-60s   <DRV>", direntry[fileview+c].name);
          break;
        }
      }
      else
      {
        sprintf(textbuffer, "                                                                    ");
      }
      color = CNORMAL;
      if ((fileview+c) == filepos) color = CEDIT;
      textbuffer[68] = 0;
      printtext(50-(MAX_FILENAME+10)/2+1, 5+c, color, textbuffer);
      if ((!filemode) && ((fileview+c) == filepos)) printbg(50-(MAX_FILENAME+10)/2+1, 5+c, cc, 68);
    }

    printtext(50-(MAX_FILENAME+10)/2+1, 6+VISIBLEFILES, 15, "PATH:   ");
    sprintf(textbuffer, "%-60s", path);
    textbuffer[MAX_FILENAME] = 0;
    color = CNORMAL;
    if (filemode == 1) color = CEDIT;
    printtext(50-(MAX_FILENAME+10)/2+9, 6+VISIBLEFILES, color, textbuffer);
    if ((filemode == 1) && (strlen(path) < MAX_FILENAME)) printbg(50-(MAX_FILENAME+10)/2+9+strlen(path), 6+VISIBLEFILES, cc, 1);

    printtext(50-(MAX_FILENAME+10)/2+1, 7+VISIBLEFILES, 15, "FILTER: ");
    sprintf(textbuffer, "%-60s", filter);
    textbuffer[MAX_FILENAME] = 0;
    color = CNORMAL;
    if (filemode == 2) color = CEDIT;
    printtext(50-(MAX_FILENAME+10)/2+9, 7+VISIBLEFILES, color, textbuffer);
    if (filemode == 2) printbg(50-(MAX_FILENAME+10)/2+9+strlen(filter), 7+VISIBLEFILES, cc, 1);

    printtext(50-(MAX_FILENAME+10)/2+1, 8+VISIBLEFILES, 15, "NAME:   ");
    sprintf(textbuffer, "%-60s", name);
    textbuffer[MAX_FILENAME] = 0;
    color = CNORMAL;
    if (filemode == 3) color = CEDIT;
    printtext(50-(MAX_FILENAME+10)/2+9, 8+VISIBLEFILES, color, textbuffer);
    if (filemode == 3) printbg(50-(MAX_FILENAME+10)/2+9+strlen(name), 8+VISIBLEFILES, cc, 1);

    if (win_quitted) exitfilesel = 0;

    if ((mouseb) && (!prevmouseb))
    {
      lastclick = DOUBLECLICKDELAY;
      lastfile = filepos;
    }
  }

  // Deallocate all used names
  for (c = 0; c < MAX_DIRFILES; c++)
  {
    if (direntry[c].name)
    {
      free(direntry[c].name);
      direntry[c].name = NULL;
    }
  }

  // Restore screen & exit
  printmainscreen();
  return exitfilesel;
}
Beispiel #16
0
JNIEXPORT jobject JNICALL jnm_getdriveinfo(JNIEnv *env, jobject obj, jobject file)
{
  jclass dic = jnismooth_dll->findClass("jsmooth.DriveInfo");
  if (dic == 0)
    {
      return NULL;
    }

  jmethodID construc = jnismooth_dll->findMethod(dic, "<init>", "()V", false);
  if (construc == 0)
    {
      return NULL;
    }

  JMethodCaller canonicalcaller("java.io.File", "java.lang.String getCanonicalPath()");
  jvalue vals[0];

  jvalue canonicalval = canonicalcaller.invoke(*jnismooth_dll, file, vals);
  jstring jcanstr = (jstring)canonicalval.l;

  jboolean copy = true;
  const char* str = jnismooth_dll->env()->GetStringUTFChars(jcanstr, &copy);
  std::string canonicalfile = str;
  jnismooth_dll->env()->ReleaseStringUTFChars(jcanstr, str);

  //  int driveType = GetDriveType();
  jobject driveinfo = jnismooth_dll->env()->NewObject(dic, construc);
  if ((canonicalfile.length()>1) && (canonicalfile[1] == ':'))
    {
      std::string driveletter = canonicalfile[0] + std::string(":\\");
      int drivetype = GetDriveType(driveletter.c_str());
      jnismooth_dll->setIntField(dic, driveinfo, "m_driveType", drivetype);

      void * pGetDiskFreeSpaceEx = (void*)GetProcAddress(GetModuleHandle("kernel32.dll"), "GetDiskFreeSpaceExA");
      long freeBytes = 0, totalBytes = -1, totalFreeBytes = 0;

      if ((pGetDiskFreeSpaceEx != 0) && (drivetype > 1))
	{
	  unsigned __int64 lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes;
	  if (GetDiskFreeSpaceEx(driveletter.c_str(), (_ULARGE_INTEGER*)&lpFreeBytesAvailable, (_ULARGE_INTEGER*)&lpTotalNumberOfBytes, (_ULARGE_INTEGER*)&lpTotalNumberOfFreeBytes))
	    {
	      freeBytes = lpFreeBytesAvailable;
	      totalBytes = lpTotalNumberOfBytes;
	      totalFreeBytes = lpTotalNumberOfFreeBytes;
	    }
	}
      else if (drivetype > 1)
	{
	  DWORD dwSectPerClust, dwBytesPerSect, dwFreeClusters, dwTotalClusters;
	  if (GetDiskFreeSpace(driveletter.c_str(), &dwSectPerClust, &dwBytesPerSect, &dwFreeClusters, &dwTotalClusters))
	    {
	      freeBytes = ((long)dwBytesPerSect * (long)dwSectPerClust * (long)dwFreeClusters);
	      totalBytes = ((long)dwBytesPerSect * (long)dwSectPerClust * (long)dwTotalClusters);
	      totalFreeBytes = ((long)dwBytesPerSect * (long)dwSectPerClust * (long)dwFreeClusters);
	    }
	}

      jnismooth_dll->setLongField(dic, driveinfo, "m_freeBytesForUser", freeBytes);      
      jnismooth_dll->setLongField(dic, driveinfo, "m_totalFreeBytes", totalFreeBytes);      
      jnismooth_dll->setLongField(dic, driveinfo, "m_totalBytes", totalBytes);

      
      if (drivetype > 1)
	{
	  char volumename[MAX_PATH+1], filesystemname[MAX_PATH+1];
	  DWORD serialnumber, maxcomposize, systemflags;
	  if (GetVolumeInformation( driveletter.c_str(), volumename, MAX_PATH, 
				    &serialnumber, &maxcomposize, &systemflags,
				    filesystemname, MAX_PATH))
	    {
	      jnismooth_dll->setIntField(dic, driveinfo, "m_serialNumber", serialnumber);
	      jnismooth_dll->setIntField(dic, driveinfo, "m_maxComponentSize", maxcomposize);
	      jnismooth_dll->setIntField(dic, driveinfo, "m_systemFlags", systemflags);

	      jstring jvolumename = jnismooth_dll->newUTFString(volumename);
	      jstring jfilesystemname = jnismooth_dll->newUTFString(filesystemname);
	      jnismooth_dll->setObjectField(dic, driveinfo, "m_volumeName", "java.lang.String", (jobject)jvolumename);
	      jnismooth_dll->setObjectField(dic, driveinfo, "m_fileSystemName", "java.lang.String", (jobject)jfilesystemname);
	    }	  
	}
    }
  
    //  jfieldID binding = broker->env()->GetFieldID(nat, "m_", "I");
  // broker->env()->SetStaticBooleanField(nat, binding, JNI_TRUE);

  return driveinfo;
}
		virtual bool IsRemote(char drive) const
		{
			char driveName[] = { drive, ':', '\\', '\0' };
			UINT type = GetDriveType(driveName);
			return (type==DRIVE_REMOTE);
		}
Beispiel #18
0
BOOL GetLogicalDrivers::Cls_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
	hComboBox = CreateWindowEx(WS_EX_DLGMODALFRAME, TEXT("COMBOBOX"), 0,
		WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST|CBS_SORT, 50, 50, 300, 400, hwnd, 0, HINSTANCE(ptr), 0);
	
	const DWORD number_of_drives = 32;
	TCHAR buffer[512];
	TCHAR* b_ptr;
	b_ptr = buffer;
	GetLogicalDriveStrings(number_of_drives, buffer);

	TCHAR letter = char(65);
	int i = 1;
	int mask = GetLogicalDrives();
	//TCHAR textt[10];
	//wsprintf(textt, TEXT("%d"), mask);
	//MessageBox(hDialog, textt, TEXT("INFO"), MB_OK);
	while (*b_ptr)
	{
		while (b_ptr[0] != letter)
		{
			letter = char(65 + i);
			++i;
		}
		int n = ((mask >> i) & 0x00000001);
		if (!n)
		{
			b_ptr = b_ptr + wcslen(b_ptr) + 1;
			continue;
		}
		
		int type = GetDriveType(b_ptr);
		TCHAR type_name[16];
		switch (type)
		{
		case DRIVE_FIXED:
			lstrcpy(type_name, TEXT(" (fixed)"));
			break;
		case DRIVE_REMOVABLE:
			lstrcpy(type_name, TEXT(" (removable)"));
			break;
		case DRIVE_REMOTE:
			lstrcpy(type_name, TEXT(" (remote)"));
			break;
		case DRIVE_CDROM:
			lstrcpy(type_name, TEXT(" (cd-rom)"));
			break;
		case DRIVE_RAMDISK:
			lstrcpy(type_name, TEXT(" (virtual)"));
			break;
		default:
			lstrcpy(type_name, TEXT(" (unknown)"));
			break;
		}
		TCHAR temp[32];
		lstrcpy(temp, b_ptr);
		lstrcat(temp, type_name);
		SendMessage(hComboBox, CB_ADDSTRING, 0, LPARAM(temp));
		b_ptr = b_ptr + wcslen(b_ptr) + 1;
	}
	
	
	return TRUE;
}
static UTF16 getNotesOnLogicalDrive(Error& error, const UTF16& sLogicalDrive)
{
	UTF16Buffer sbVolName(MAX_PATH+1);
	UTF16Buffer sbFSType(MAX_PATH+1);

	if (!GetVolumeInformation(sLogicalDrive.ptr(), sbVolName.ptr(), 
		sbVolName.flength(), NULL, NULL, NULL, sbFSType.ptr(), sbFSType.flength()))
	{
		error.what(WindowsError::getLastError());
		error.who(L"GetVolumeInformation");
		return UTF16();
	}
	
	UTF16 sVolName = sbVolName;
	UTF16 sFSType = sbFSType;

	if (!sVolName.empty())
		sVolName = sVolName + " ";
	
	if (!sFSType.empty())
		sFSType = sFSType + " ";

	UTF16 sDriveType;

	switch (GetDriveType(sLogicalDrive.ptr()))
	{
	case DRIVE_NO_ROOT_DIR: sDriveType = L"No Root Dir "; break;
	case DRIVE_REMOVABLE: sDriveType = L"Removable "; break;
	case DRIVE_FIXED: sDriveType = L"Fixed "; break;
	case DRIVE_CDROM: sDriveType = L"CDROM "; break;
	case DRIVE_RAMDISK: sDriveType = L"RAM Disk "; break;
	default: sDriveType = L"Unknown ";
	}

	UTF16 sSizeInfo;

	UInt64 iBytesFree, iTotalBytes;
	ULARGE_INTEGER ulgFreeBytesAvailable, ulgTotalNumberOfBytes;
	if (GetDiskFreeSpaceEx(sLogicalDrive.ptr(), &ulgFreeBytesAvailable, &ulgTotalNumberOfBytes, NULL))
	{
		iBytesFree = ulgFreeBytesAvailable.QuadPart;
		iTotalBytes = ulgTotalNumberOfBytes.QuadPart;

		int iUnit = 0;
		for (UInt64 i = iTotalBytes; i > 0; i >>= 10)
			iUnit++;
		UTF16 sUnit;
		switch (iUnit)
		{
		case 0: iUnit = 1; sUnit = L"B"; break;
		case 1: sUnit = L"B"; break;
		case 2: sUnit = L"KB"; break;
		case 3: sUnit = L"MB"; break;
		case 4: sUnit = L"GB"; break;
		case 5: sUnit = L"TB"; break;
		case 6: sUnit = L"PB"; break;
		case 7: sUnit = L"EB"; break;
		case 8: sUnit = L"ZB"; break;
		case 9: sUnit = L"YB"; break;
		default: sUnit = L"??"; break;
		}

		Real64 fBytesFree = Real64(iBytesFree) / Real64(1ULL << (10*(iUnit-1)));
		Real64 fTotalBytes = Real64(iTotalBytes) / Real64(1ULL << (10*(iUnit-1)));
		Real64 fBytesUsed = fTotalBytes - fBytesFree;

		sSizeInfo = UTF16::format(L"%d/%d%s ", UInt32(fBytesUsed), UInt32(fTotalBytes), sUnit.ptr());
	}
Beispiel #20
0
INT IsDirectory(LPCWSTR szDirectoryName)
{
	

	HANDLE hFind;
	WIN32_FIND_DATAW fd;
	
	int ret=TRUE;
	
	if (szDirectoryName[0]==L'\0')
		return 0;
	
	if (szDirectoryName[1]==L'\0')
		return 0;
	
	if (szDirectoryName[2]==L'\0')
		return 0;
	
	if (szDirectoryName[1]==L':' && szDirectoryName[2]==L'\\' && szDirectoryName[3]==L'\0')
	{
		switch (GetDriveTypeW(szDirectoryName))
		{
		case DRIVE_UNKNOWN:
		case DRIVE_NO_ROOT_DIR:
			return 0;
		case DRIVE_FIXED:
			return 1;
		default:
			return 2;
		}
	}
	
	

	// Taking last '\\' 
	LPWSTR szPath;
	SIZE_T dwPathLen=istrlenw(szDirectoryName);
	if (szDirectoryName[dwPathLen-1]==L'\\' && dwPathLen>3)
	{
		szPath=new WCHAR[dwPathLen+5];
		--dwPathLen;
		MemCopyW(szPath,szDirectoryName,dwPathLen);
		szPath[dwPathLen]='\0';
	}
	else
		szPath=LPWSTR(szDirectoryName);

	

	hFind=FindFirstFileW(szPath,&fd);
	if (hFind!=INVALID_HANDLE_VALUE)
	{
		while (!(fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) && ret)
			ret=FindNextFileW(hFind,&fd);
	
		if (szPath!=szDirectoryName)
			delete[] szPath;

		FindClose(hFind);	
		if (ret)
		{
			if (szDirectoryName[0]==L'\\')
			{
				if (szDirectoryName[1]==L'\\')
					return 2;
				switch (GetDriveType(NULL))
				{
				case DRIVE_UNKNOWN:
				case DRIVE_NO_ROOT_DIR:
					return 0;
				case DRIVE_FIXED:
					return 1;
				default:
					return 2;
				}
 
			}
			if (szDirectoryName[1]==L':' && szDirectoryName[2]==L'\\')
			{
				WCHAR szTemp[4]=L"X:\\";
				szTemp[0]=szDirectoryName[0];

				switch (GetDriveTypeW(szTemp))
				{
				case DRIVE_UNKNOWN:
					return 0;
				case DRIVE_FIXED:
					return 1;
				default:
					return 2;
				}
			}
		}
		return 0;
	}
	else if (szDirectoryName[0]==L'\\' && szDirectoryName[1]==L'\\')
	{
		
		// UNC share name
		if (szPath==szDirectoryName)
		{
			szPath=new WCHAR[dwPathLen+5];
			CopyMemory(szPath,szDirectoryName,dwPathLen*2);
		}		
		CopyMemory(szPath+dwPathLen,L"\\*.*",5*2);

		hFind=FindFirstFileW(szPath,&fd);
		delete[] szPath;
		if (hFind==INVALID_HANDLE_VALUE)
			return 0;
		// Is this really needed, e.g. \\pc\c$ does not have '.' in directory list
		//ret=1;
		//while ((fd.cFileName[0]!='.' || fd.cFileName[1]!='\0') && ret==1)
		//	ret=FindNextFile(hFind,&fd);
		FindClose(hFind);
		//return ret?2:0;
		return 2;
	}
	
	
	
	if (szPath!=szDirectoryName)
		delete[] szPath;
	return 0;
}
Beispiel #21
0
/*
** Updates the current disk free space value.
**
*/
void MeasureDiskSpace::UpdateValue()
{
	if (!m_Drive.empty())
	{
		const WCHAR* drive = m_Drive.c_str();
		UINT type = GetDriveType(drive);

		if (m_Type)
		{
			switch (type)
			{
			case DRIVE_UNKNOWN:
			case DRIVE_NO_ROOT_DIR:
				m_Value = DRIVETYPE_REMOVED;
				m_StringValue = L"Removed";
				break;
			case DRIVE_REMOVABLE:
				m_Value = DRIVETYPE_REMOVABLE;
				m_StringValue = L"Removable";
				break;
			case DRIVE_FIXED:
				m_Value = DRIVETYPE_FIXED;
				m_StringValue = L"Fixed";
				break;
			case DRIVE_REMOTE:
				m_Value = DRIVETYPE_NETWORK;
				m_StringValue = L"Network";
				break;
			case DRIVE_CDROM:
				m_Value = DRIVETYPE_CDROM;
				m_StringValue = L"CDRom";
				break;
			case DRIVE_RAMDISK:
				m_Value = DRIVETYPE_RAM;
				m_StringValue = L"Ram";
				break;
			default:
				m_Value = DRIVETYPE_ERROR;
				m_StringValue = L"Error";
				break;
			}
		}
		else
		{
			BOOL sizeResult = FALSE;
			ULONGLONG i64TotalBytes, i64FreeBytes;

			if (type != DRIVE_NO_ROOT_DIR &&
				type != DRIVE_CDROM &&
				(!m_IgnoreRemovable || type != DRIVE_REMOVABLE))  // Ignore CD-ROMS and removable drives
			{
				if (!m_DiskQuota)
				{
					sizeResult = GetDiskFreeSpaceEx(drive, nullptr, (PULARGE_INTEGER)&i64TotalBytes, (PULARGE_INTEGER)&i64FreeBytes);
				}
				else
				{
					sizeResult = GetDiskFreeSpaceEx(drive, (PULARGE_INTEGER)&i64FreeBytes, (PULARGE_INTEGER)&i64TotalBytes, nullptr);
				}
			}

			if (sizeResult)
			{
				m_Value = (double)(__int64)((m_Total) ? i64TotalBytes : i64FreeBytes);

				if (i64TotalBytes != m_OldTotalBytes)
				{
					// Total size was changed, so set new max value.
					m_MaxValue = (double)(__int64)i64TotalBytes;
					m_OldTotalBytes = i64TotalBytes;
				}
			}
			else
			{
				m_Value = 0.0;
				m_MaxValue = 0.0;
				m_OldTotalBytes = 0;
			}

			if (m_Label)
			{
				BOOL labelResult = FALSE;
				WCHAR volumeName[MAX_PATH + 1];

				if (type != DRIVE_NO_ROOT_DIR &&
					(!m_IgnoreRemovable || type != DRIVE_REMOVABLE))  // Ignore removable drives
				{
					labelResult = GetVolumeInformation(drive, volumeName, MAX_PATH + 1, nullptr, nullptr, nullptr, nullptr, 0);
				}

				m_StringValue = (labelResult) ? volumeName : L"";
			}
			else if (!m_StringValue.empty())
			{
				m_StringValue.clear();
			}
		}
	}
}
Beispiel #22
0
// !!UNC
void init_posix_emu(void)
{
	if(!validate_stat_struct) {
		ErrorAlert( "Invalid struct my_stat -- edit posix_emu.h" );
		QuitEmulator();
	}

#if DEBUG_EXTFS
	debug_extfs = PrefsFindInt16("debugextfs");

	debug_extfs = DB_EXTFS_LOUD;

	if(debug_extfs != DB_EXTFS_NONE) {
		extfs_log_open( EXTFS_LOG_FILE_NAME );
	}
#endif

	// We cannot use ExtFS "RootPath" because of the virtual desktop.
	if(PrefsFindBool("enableextfs")) {
		PrefsReplaceString("extfs", "");
	} else {
		PrefsRemoveItem("extfs");
		D(bug("extfs disabled by user\n"));
#if DEBUG_EXTFS
		extfs_log_close();
#endif
		return;
	}

	const char *extdrives = PrefsFindString("extdrives");

	// Set up drive list.
	size_t outinx = 0;
	for( TCHAR letter = TEXT('A'); letter <= TEXT('Z'); letter++ ) {
		if(extdrives && !strchr(extdrives,letter)) continue;
		TCHAR rootdir[20];
		_sntprintf( rootdir, lengthof(rootdir), TEXT("%c:\\"), letter );
		use_streams[ letter - 'A' ] = false;
		switch(GetDriveType(rootdir)) {
			case DRIVE_FIXED:
			case DRIVE_REMOTE:
			case DRIVE_RAMDISK:
				// TODO: NTFS AFP?
				// fall
			case DRIVE_REMOVABLE:
			case DRIVE_CDROM:
				if(outinx < lengthof(host_drive_list)) {
					host_drive_list[outinx] = letter;
					outinx += 2;
				}
		}
	}

	// Set up virtual desktop root.
	// TODO: this should be customizable.
	GetModuleFileName( NULL, virtual_root, lengthof(virtual_root) );
	TCHAR *p = _tcsrchr( virtual_root, TEXT('\\') );
	if(p) {
		_tcscpy( ++p, desktop_name );
	} else {
		// should never happen
		_sntprintf( virtual_root, lengthof(virtual_root), TEXT("C:\\%s"), desktop_name );
	}
	CreateDirectory( virtual_root, 0 );

	// Set up an icon looking like "My Computer"
	// Can be overwritten just like any other folder custom icon.
	if(my_access(custom_icon_name,0) != 0) {
		int fd = my_creat( custom_icon_name, 0 );
		if(fd >= 0) {
			my_close(fd);
			fd = open_rfork( custom_icon_name, O_RDWR|O_CREAT );
			if(fd >= 0) {
				my_write( fd, my_comp_icon, sizeof(my_comp_icon) );
				my_close(fd);
				static uint8 host_finfo[SIZEOF_FInfo];
				uint32 finfo = Host2MacAddr(host_finfo);
				get_finfo(custom_icon_name, finfo, 0, false);
				WriteMacInt16(finfo + fdFlags, kIsInvisible);
				set_finfo(custom_icon_name, finfo, 0, false);
				get_finfo(my_computer, finfo, 0, true);
				WriteMacInt16(finfo + fdFlags, ReadMacInt16(finfo + fdFlags) | kHasCustomIcon);
				set_finfo(my_computer, finfo, 0, true);
			} else {
				my_remove(custom_icon_name);
			}
		}
	}
}
Beispiel #23
0
BOOL bigfilehelper::GetAutoDestDirFromSize(CString& strDir)
{
    BOOL retval = FALSE;
    CAtlArray<TCHAR> buffer;
    TCHAR* pBuffer = NULL;
    DWORD dwSize;
    CAtlList<CString> logicalDrvs;
    CString strDrv;
    POSITION pos = NULL;
    POSITION max_size_pos = NULL;
    ULONGLONG uMaxSize = 0;
    DWORD dwSectorsPerCluster;
    DWORD dwBytesPerSector;
    DWORD dwNumberOfFreeClusters;
    DWORD dwTotalNumberOfClusters;
    CString strSysDrv;
    TCHAR szVolName[MAX_PATH+1] = { 0 };
    TCHAR szFileSystem[MAX_PATH+1] = { 0 };
    BOOL fRetCode;

    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

    if (!GetSystemDrive(strSysDrv))
        goto clean0;

    buffer.SetCount(512);
    pBuffer = buffer.GetData();
    dwSize = (DWORD)buffer.GetCount();
    memset(pBuffer, 0, dwSize * sizeof(TCHAR));
    dwSize = GetLogicalDriveStrings(dwSize, buffer.GetData());

    if (dwSize > 2) 
    {
        strDrv = pBuffer;
        logicalDrvs.AddTail(strDrv);

        for (DWORD i = 3; i < dwSize; ++i) 
        {
            if (pBuffer[i] != 0 && pBuffer[i - 1] == 0) 
            {
                strDrv = pBuffer + i;
                logicalDrvs.AddTail(strDrv);
            }
        }
    }

    pos = logicalDrvs.GetHeadPosition();
    while (pos)
    {
        POSITION current = pos;
        CString _drv = logicalDrvs.GetNext(pos);
        _drv.MakeLower();
        if (_drv == _T("a:\\") || _drv == _T("b:\\"))
        {
            logicalDrvs.RemoveAt(current);
            continue;
        }

        UINT uType = GetDriveType(_drv);
        if (uType != DRIVE_FIXED &&
            uType != DRIVE_REMOVABLE)
        {
            logicalDrvs.RemoveAt(current);
            continue;
        }

        if (strSysDrv.CompareNoCase(_drv)==0)
        {
            logicalDrvs.RemoveAt(current);
            continue;
        }

        RtlZeroMemory(szVolName, sizeof(szVolName));
        RtlZeroMemory(szFileSystem, sizeof(szFileSystem));
        fRetCode = GetVolumeInformation(
            _drv,
            szVolName,
            MAX_PATH+1,
            NULL,
            NULL,
            NULL,
            szFileSystem,
            MAX_PATH+1
            );
        if (!fRetCode)
        {
            logicalDrvs.RemoveAt(current);
            continue;
        }
    }

    pos = logicalDrvs.GetHeadPosition();
    while (pos)
    {
        POSITION current = pos;
        const CString& _drv = logicalDrvs.GetNext(pos);
        BOOL fRetCode = GetDiskFreeSpace(
            _drv,
            &dwSectorsPerCluster,
            &dwBytesPerSector,
            &dwNumberOfFreeClusters,
            &dwTotalNumberOfClusters
            );
        if (!fRetCode)
            continue;

        ULONGLONG uCurrentFreeSize = (ULONGLONG)dwNumberOfFreeClusters * dwSectorsPerCluster * dwBytesPerSector;
        if (uCurrentFreeSize > uMaxSize)
        {
            max_size_pos = current;
            uMaxSize = uCurrentFreeSize;
        }
    }
    if (max_size_pos==NULL)
        goto clean0;
    strDir = logicalDrvs.GetAt(max_size_pos);
    strDir += _T("系统盘大文件");

    retval = TRUE;

clean0:
    return retval;
}
Beispiel #24
0
DWORD
ScanForCdromDevices(
    VOID
    )

/*++

Routine Description:


    Scan through device chain for CDROM devices.  For each one
    that is found, allocate storage in the gDevices array and
    fill in fields available at this time.


Arguments:


    none


Return Value:


    Number of CDROM devices found.


--*/


{
    CHAR        DriveRoot[]="A:\\", DevRoot[]="\\\\.\\A:";
    int         NumCdroms;
    HANDLE      TmpHandle;
    DWORD       dwDrives;
    CHAR        s[255];


    //
    // Find what drive letters are valid
    //

    dwDrives = GetLogicalDrives();

    NumCdroms = 0;

    //
    // Loop through drives letters one by one, checking to see if it's a Cdrom.
    //
    for ( DriveRoot[0]='A'; dwDrives != 0; dwDrives = dwDrives>>1 ) {

        //
        // If the current DriveLetter Exists and is a Cdrom
        //
        if ( (dwDrives & 0x1) && (GetDriveType(DriveRoot) == DRIVE_CDROM) ) {

            DevRoot[4] = DriveRoot[0];


            if ((NumCdroms < (INT)gNumCdDevices) && (gDevices[NumCdroms]!=NULL)) {

                LocalFree( (HLOCAL)gDevices[ NumCdroms ] );

            }

            gDevices[ NumCdroms ] = (PCDROM)LocalAlloc( LPTR, sizeof( CDROM ) );

            if (gDevices[ NumCdroms ]==NULL) {

                sprintf( s, IdStr( STR_NO_RES ), GetLastError() );
                MyFatalExit( s );

            }

            gDevices[ NumCdroms ]->drive = DriveRoot[0];
            gDevices[ NumCdroms ]->State = NO_CD;


            //
            // Open the Cdrom for exclusive access
            //
            TmpHandle = CreateFile( DevRoot,
                                    GENERIC_READ,
                                    FILE_SHARE_READ,
                                    NULL,
                                    OPEN_EXISTING,
                                    FILE_ATTRIBUTE_NORMAL,
                                    NULL
                                   );

            if (TmpHandle == INVALID_HANDLE_VALUE) {

                gDevices[ NumCdroms ]->hCd = NULL;

            } else {

                gDevices[ NumCdroms ]->hCd = TmpHandle;

            }

            NumCdroms++;

        }

        DriveRoot[0] = DriveRoot[0]+1;

    }

    return(NumCdroms);


/****************************************************************
    DWORD        status;
    TCHAR        s[ 16 ];
    ULONG        cdDevice = 0;
    HANDLE       TmpHandle;
    int          cdnum = 0;

    //
    // Scan drive chain ("a:" thru "z:") for cdrom drives
    //

    for( cdDevice=0; cdDevice<26; cdDevice++ ) {

        sprintf( s, "\\\\.\\%c:", cdDevice + (INT)'A' );
        if (GetDriveType( &s[4*sizeof(TCHAR)] )==DRIVE_CDROM) {

            TmpHandle = CreateFile( s,
                                    GENERIC_READ,
                                    FILE_SHARE_READ,
                                    NULL,
                                    OPEN_EXISTING,
                                    FILE_ATTRIBUTE_NORMAL,
                                    NULL
                                   );

            if (TmpHandle!=INVALID_HANDLE_VALUE) {

                //
                // Found cdrom drive!
                //

                if ((cdnum<(INT)gNumCdDevices) && (gDevices[ cdnum ]!=NULL))
                    LocalFree( (HLOCAL)gDevices[ cdnum ] );
                gDevices[ cdnum ] = (PCDROM)LocalAlloc( LPTR, sizeof( CDROM ) );
                if (gDevices[ cdnum ]==NULL)
                    MyFatalExit( IdStr( STR_NO_RES ) );
                gDevices[ cdnum ]->hCd = TmpHandle;
                gDevices[ cdnum ]->drive = (CHAR)(cdDevice + (INT)'A');
                gDevices[ cdnum ]->State = NO_CD;
                cdnum++;

            }

        }

    }

    return( cdnum );

***************************************************************/

}
Beispiel #25
0
// HasEnoughDiskSpace
//------------------------------------------------------------------------------
bool Worker::HasEnoughDiskSpace()
{
    #if defined( __WINDOWS__ )
        // Only check disk space every few seconds
        float elapsedTime = m_TimerLastDiskSpaceCheck.GetElapsedMS();
        if ( ( elapsedTime < 15000.0f ) && ( m_LastDiskSpaceResult != -1 ) )
        {
            return ( m_LastDiskSpaceResult != 0 );
        }
        m_TimerLastDiskSpaceCheck.Start();
         
        static const uint64_t MIN_DISK_SPACE = 1024 * 1024 * 1024; // 1 GiB 
         
        DWORD logicalDrives = GetLogicalDrives();
        DWORD driveMask = 1;
        char driveLetter = 'a';
        char drivePath[32];
        int validDriveCount = 0;    // This is to insure we find at least one drive...
         
        // Enumerate all drive letters.
        for ( uint32_t i = 0; i < 26; ++i, ++driveLetter, driveMask *= 2 )
        {
            if ( (logicalDrives & driveMask) != 0 )
            {
                // This letter is used.
                sprintf_s( drivePath, sizeof(drivePath), "%c:\\", driveLetter );
         
                UINT driveType = GetDriveType( drivePath );
                if ( driveType == DRIVE_FIXED )
                {
                    // This is a fixed frive.
                    unsigned __int64 freeBytesAvailable = 0;
                    unsigned __int64 totalNumberOfBytes = 0;
                    unsigned __int64 totalNumberOfFreeBytes = 0;
         
                    // Check available disk space
                    BOOL result = GetDiskFreeSpaceExA( drivePath, (PULARGE_INTEGER)&freeBytesAvailable, (PULARGE_INTEGER)&totalNumberOfBytes, (PULARGE_INTEGER)&totalNumberOfFreeBytes );
                    if ( result )
                    {
                        if ( freeBytesAvailable < MIN_DISK_SPACE )
                        {
                            // The drive doesn't have enough free space. Exclude this machine from workers.
                            // It is simpler to exclude the machine from the build when any of its drive has not enough space
                            // than trying to figure out which drives are really used by Fastbuild especially in the context of symlinks, hardlinks, etc...
                            m_LastDiskSpaceResult = 0;
                            return false;
                        }
         
                        // At least one drive found.
                        ++validDriveCount;
                    }
                    else
                    {
                        // There is something wrong with the drives...
                        m_LastDiskSpaceResult = 0;
                        return false;
                    }
                }
            }
        }
        
        // return true if we've found at least one disk drive. 
        // This is paranoid but I like being paranoid. If we reach this line it is pretty much impossible for validDriveCount to be 0.    
        m_LastDiskSpaceResult = validDriveCount > 0;
        return m_LastDiskSpaceResult != 0;
    #else
        return true; // TODO:MAC TODO:LINUX Implement disk space checks
    #endif
}
Beispiel #26
0
// takes a root drive path, returns true if it is a cdrom drive
bool is_cdrom(const TCHAR* drive)
{
    return (DRIVE_CDROM == GetDriveType(drive));
}
Beispiel #27
0
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);
}
Beispiel #28
0
bool CSysInfo::GetDiskSpace(const CStdString drive,int& iTotal, int& iTotalFree, int& iTotalUsed, int& iPercentFree, int& iPercentUsed)
{
  bool bRet= false;
  ULARGE_INTEGER ULTotal= { { 0 } };
  ULARGE_INTEGER ULTotalFree= { { 0 } };

  if( !drive.IsEmpty() && !drive.Equals("*") )
  {
#ifdef _WIN32
    UINT uidriveType = GetDriveType(( drive + ":\\" ));
    if(uidriveType != DRIVE_UNKNOWN && uidriveType != DRIVE_NO_ROOT_DIR)
#endif
      bRet= ( 0 != GetDiskFreeSpaceEx( ( drive + ":\\" ), NULL, &ULTotal, &ULTotalFree) );
  }
  else
  {
    ULARGE_INTEGER ULTotalTmp= { { 0 } };
    ULARGE_INTEGER ULTotalFreeTmp= { { 0 } };
#ifdef _WIN32
    char* pcBuffer= NULL;
    DWORD dwStrLength= GetLogicalDriveStrings( 0, pcBuffer );
    if( dwStrLength != 0 )
    {
      dwStrLength+= 1;
      pcBuffer= new char [dwStrLength];
      GetLogicalDriveStrings( dwStrLength, pcBuffer );
      int iPos= 0;
      do {
        if( DRIVE_FIXED == GetDriveType( pcBuffer + iPos  ) &&
            GetDiskFreeSpaceEx( ( pcBuffer + iPos ), NULL, &ULTotal, &ULTotalFree ) )
        {
          ULTotalTmp.QuadPart+= ULTotal.QuadPart;
          ULTotalFreeTmp.QuadPart+= ULTotalFree.QuadPart;
        }
        iPos += (strlen( pcBuffer + iPos) + 1 );
      }while( strlen( pcBuffer + iPos ) > 0 );
    }
    delete[] pcBuffer;
#else // for linux and osx
    static const char *drv_letter[] = { "C:\\", "E:\\", "F:\\", "G:\\", "X:\\", "Y:\\", "Z:\\", NULL };
    for( int i = 0; drv_letter[i]; i++)
    {
      if( GetDiskFreeSpaceEx( drv_letter[i], NULL, &ULTotal, &ULTotalFree ) )
      {
        ULTotalTmp.QuadPart+= ULTotal.QuadPart;
        ULTotalFreeTmp.QuadPart+= ULTotalFree.QuadPart;
      }
    }
#endif
    if( ULTotalTmp.QuadPart || ULTotalFreeTmp.QuadPart )
    {
      ULTotal.QuadPart= ULTotalTmp.QuadPart;
      ULTotalFree.QuadPart= ULTotalFreeTmp.QuadPart;
      bRet= true;
    }
  }

  if( bRet )
  {
    iTotal = (int)( ULTotal.QuadPart / MB );
    iTotalFree = (int)( ULTotalFree.QuadPart / MB );
    iTotalUsed = iTotal - iTotalFree;
    iPercentUsed = (int)( 100.0f * ( ULTotal.QuadPart - ULTotalFree.QuadPart ) / ULTotal.QuadPart + 0.5f );
    iPercentFree = 100 - iPercentUsed;
  }

  return bRet;
}
Beispiel #29
0
//----------------------------------------------------------------------
//
// WMain
//
// Engine. Just get command line switches and fire off a format. This
// could also be done in a GUI like Explorer does when you select a
// drive and run a check on it.
//
// We do this in UNICODE because the chkdsk command expects PWCHAR
// arguments.
//
//----------------------------------------------------------------------
int
_tmain(int argc, TCHAR *argv[])
{
	int badArg;
	DWORD media = FMIFS_HARDDISK;
	DWORD driveType;
	TCHAR fileSystem[1024];
	TCHAR volumeName[1024];
	TCHAR input[1024];
	DWORD serialNumber;
	DWORD flags, maxComponent;
	ULARGE_INTEGER freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes;
#ifndef UNICODE
	WCHAR RootDirectoryW[MAX_PATH], FormatW[MAX_PATH], LabelW[MAX_PATH];
#endif
	TCHAR szMsg[RC_STRING_MAX_SIZE];

	//
	// Get function pointers
	//
	if( !LoadFMIFSEntryPoints()) {
		LoadStringAndOem( GetModuleHandle(NULL), STRING_FMIFS_FAIL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf("%s", szMsg);
		return -1;
	}

	//
	// Parse command line
	//
	if( (badArg = ParseCommandLine( argc, argv ))) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_UNKNOW_ARG, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf(szMsg, argv[badArg] );

		Usage(argv[0]);
		return -1;
	}

	//
	// Get the drive's format
	//
	if( !Drive ) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_DRIVE_PARM, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf(szMsg);
		Usage( argv[0] );
		return -1;

	} else {

		_tcscpy( RootDirectory, Drive );
	}
	RootDirectory[2] = _T('\\');
	RootDirectory[3] = _T('\0');

	//
	// See if the drive is removable or not
	//
	driveType = GetDriveType( RootDirectory );

	if( driveType == 0 ) {
		LoadStringAndOem( GetModuleHandle(NULL), STRING_ERROR_DRIVE_TYPE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error( szMsg, GetLastError());
		return -1;
	}
	else if ( driveType == 1 )
	{
		LoadString( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error( szMsg, GetLastError());
		return -1;
	}

	if( driveType != DRIVE_FIXED ) {
		LoadStringAndOem( GetModuleHandle(NULL), STRING_INSERT_DISK, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf(szMsg, RootDirectory[0] );
		_fgetts( input, sizeof(input)/2, stdin );

		media = FMIFS_FLOPPY;
	}

	//
	// Determine the drive's file system format
	//
	if( !GetVolumeInformation( RootDirectory,
						volumeName, sizeof(volumeName)/2,
						&serialNumber, &maxComponent, &flags,
						fileSystem, sizeof(fileSystem)/2)) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error( szMsg, GetLastError());
		return -1;
	}

	if( !GetDiskFreeSpaceEx( RootDirectory,
			&freeBytesAvailableToCaller,
			&totalNumberOfBytes,
			&totalNumberOfFreeBytes )) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME_SIZE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error( szMsg, GetLastError());
		return -1;
	}
	LoadStringAndOem( GetModuleHandle(NULL), STRING_FILESYSTEM, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
	_tprintf(szMsg, fileSystem );

	//
	// Make sure they want to do this
	//
	if( driveType == DRIVE_FIXED ) {

		if( volumeName[0] ) {

			while(1 ) {

				LoadStringAndOem( GetModuleHandle(NULL), STRING_LABEL_NAME_EDIT, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
				_tprintf(szMsg, RootDirectory[0] );
				_fgetts( input, sizeof(input)/2, stdin );
				input[ _tcslen( input ) - 1] = 0;

				if( !_tcsicmp( input, volumeName )) {

					break;
				}
				LoadStringAndOem( GetModuleHandle(NULL), STRING_ERROR_LABEL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
				_tprintf("%s", szMsg);
			}
		}

		LoadStringAndOem( GetModuleHandle(NULL), STRING_YN_FORMAT, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf(szMsg, RootDirectory[0] );

		LoadStringAndOem( GetModuleHandle(NULL), STRING_YES_NO_FAQ, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);

		while( 1 ) {
			_fgetts( input, sizeof(input)/2, stdin );
			if(_strnicmp(&input[0],&szMsg[0],1) == 0) break;
			if(_strnicmp(&input[0],&szMsg[1],1) == 0) {
				_tprintf(_T("\n"));
				return 0;
			}
		}
		media = FMIFS_HARDDISK;
	}

	//
	// Tell the user we're doing a long format if appropriate
	//
	if( !QuickFormat ) {

		LoadString( GetModuleHandle(NULL), STRING_VERIFYING, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);

		if( totalNumberOfBytes.QuadPart > 1024*1024*10 ) {

			_tprintf(_T("%s %luM\n"),szMsg, (DWORD) (totalNumberOfBytes.QuadPart/(1024*1024)));

		} else {

			_tprintf(_T("%s %.1fM\n"),szMsg,
				((float)(LONGLONG)totalNumberOfBytes.QuadPart)/(float)(1024.0*1024.0));
		}
	} else {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_FAST_FMT, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		if( totalNumberOfBytes.QuadPart > 1024*1024*10 ) {

			_tprintf(_T("%s %luM\n"),szMsg, (DWORD) (totalNumberOfBytes.QuadPart/(1024*1024)));

		} else {

			_tprintf(_T("%s %.2fM\n"),szMsg,
				((float)(LONGLONG)totalNumberOfBytes.QuadPart)/(float)(1024.0*1024.0));
		}
		LoadStringAndOem( GetModuleHandle(NULL), STRING_CREATE_FSYS, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf("%s", szMsg);
	}

	//
	// Format away!
	//
#ifndef UNICODE
	MultiByteToWideChar(CP_ACP, 0, RootDirectory, -1, RootDirectoryW, MAX_PATH);
	MultiByteToWideChar(CP_ACP, 0, Format, -1, FormatW, MAX_PATH);
	MultiByteToWideChar(CP_ACP, 0, Label, -1, LabelW, MAX_PATH);
	FormatEx( RootDirectoryW, media, FormatW, LabelW, QuickFormat,
			ClusterSize, FormatExCallback );
#else
	FormatEx( RootDirectory, media, Format, Label, QuickFormat,
			ClusterSize, FormatExCallback );
#endif
	if( Error ) return -1;
	LoadStringAndOem( GetModuleHandle(NULL), STRING_FMT_COMPLETE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
	_tprintf("%s", szMsg);

	//
	// Enable compression if desired
	//
	if( CompressDrive ) {

#ifndef UNICODE
		MultiByteToWideChar(CP_ACP, 0, RootDirectory, -1, RootDirectoryW, MAX_PATH);
		if( !EnableVolumeCompression( RootDirectoryW, TRUE )) {
#else
		if( !EnableVolumeCompression( RootDirectory, TRUE )) {
#endif

			LoadStringAndOem( GetModuleHandle(NULL), STRING_VOL_COMPRESS, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
			_tprintf("%s", szMsg);
		}
	}

	//
	// Get the label if we don't have it
	//
	if( !GotALabel ) {

		LoadString( GetModuleHandle(NULL), STRING_ENTER_LABEL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		_tprintf("%s", szMsg);
		_fgetts( input, sizeof(LabelString)/2, stdin );

		input[ _tcslen(input)-1] = 0;
		if( !SetVolumeLabel( RootDirectory, input )) {

			LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_LABEL, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
			PrintWin32Error(szMsg, GetLastError());
			return -1;
		}
	}

	if( !GetVolumeInformation( RootDirectory,
						volumeName, sizeof(volumeName)/2,
						&serialNumber, &maxComponent, &flags,
						fileSystem, sizeof(fileSystem)/2)) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error( szMsg, GetLastError());
		return -1;
	}

	//
	// Print out some stuff including the formatted size
	//
	if( !GetDiskFreeSpaceEx( RootDirectory,
			&freeBytesAvailableToCaller,
			&totalNumberOfBytes,
			&totalNumberOfFreeBytes )) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME_SIZE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error(szMsg, GetLastError());
		return -1;
	}

	LoadStringAndOem( GetModuleHandle(NULL), STRING_FREE_SPACE, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
	_tprintf(szMsg, totalNumberOfBytes.QuadPart, totalNumberOfFreeBytes.QuadPart );

	//
	// Get the drive's serial number
	//
	if( !GetVolumeInformation( RootDirectory,
						volumeName, sizeof(volumeName)/2,
						&serialNumber, &maxComponent, &flags,
						fileSystem, sizeof(fileSystem)/2)) {

		LoadStringAndOem( GetModuleHandle(NULL), STRING_NO_VOLUME, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
		PrintWin32Error( szMsg, GetLastError());
		return -1;
	}
	LoadStringAndOem( GetModuleHandle(NULL), STRING_SERIAL_NUMBER, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);
	_tprintf(szMsg, (unsigned int)(serialNumber >> 16),
					(unsigned int)(serialNumber & 0xFFFF) );

	return 0;
}
Beispiel #30
0
//=============================================================================
// Function: GetBasicFlags
// Purpose: Set basic flags, primarily wxFS_VOL_REMOTE and wxFS_VOL_REMOVABLE.
// Notes: - Local and mapped drives are mounted by definition.  We have no
//          way to determine mounted status of network drives, so assume that
//          all drives are mounted, and let the caller decide otherwise.
//        - Other flags are 'best guess' from type of drive.  The system will
//          not report the file attributes with any degree of accuracy.
//=============================================================================
static unsigned GetBasicFlags(const wxChar* filename)
{
    unsigned flags = wxFS_VOL_MOUNTED;

    //----------------------------------
    // 'Best Guess' based on drive type.
    //----------------------------------
    wxFSVolumeKind type;
    switch(GetDriveType(filename))
    {
    case DRIVE_FIXED:
        type = wxFS_VOL_DISK;
        break;

    case DRIVE_REMOVABLE:
        flags |= wxFS_VOL_REMOVABLE;
        type = wxFS_VOL_FLOPPY;
        break;

    case DRIVE_CDROM:
        flags |= wxFS_VOL_REMOVABLE | wxFS_VOL_READONLY;
        type = wxFS_VOL_CDROM;
        break;

    case DRIVE_REMOTE:
        flags |= wxFS_VOL_REMOTE;
        type = wxFS_VOL_NETWORK;
        break;

    case DRIVE_NO_ROOT_DIR:
        flags &= ~wxFS_VOL_MOUNTED;
        type = wxFS_VOL_OTHER;
        break;

    default:
        type = wxFS_VOL_OTHER;
        break;
    }

    //-----------------------------------------------------------------------
    // The following most likely will not modify anything not set above,
    // and will not work at all for network shares or empty CD ROM drives.
    // But it is a good check if the Win API ever gets better about reporting
    // this information.
    //-----------------------------------------------------------------------
    SHFILEINFO fi;
    long rc = SHGetFileInfo(filename, 0, &fi, sizeof(fi), SHGFI_ATTRIBUTES);
    if (!rc)
    {
        // this error is not fatal, so don't show a message to the user about
        // it, otherwise it would appear every time a generic directory picker
        // dialog is used and there is a connected network drive
        wxLogLastError(wxT("SHGetFileInfo"));
    }
    else
    {
        if (fi.dwAttributes & SFGAO_READONLY)
            flags |= wxFS_VOL_READONLY;
        if (fi.dwAttributes & SFGAO_REMOVABLE)
            flags |= wxFS_VOL_REMOVABLE;
    }

    //------------------
    // Flags are cached.
    //------------------
    s_fileInfo[filename] = FileInfo(flags, type);

    return flags;
} // GetBasicFlags