예제 #1
0
void CDirstatDoc::PerformUserDefinedCleanup(const USERDEFINEDCLEANUP *udc, CItem *item) throw(CException *)
{
	CWaitCursor wc;

	CString path= item->GetPath();

	bool isDirectory= item->GetType() == IT_DRIVE || item->GetType() == IT_DIRECTORY || item->GetType() == IT_FILESFOLDER;

	// Verify that path still exists
	if (isDirectory)
	{
		if (!FolderExists(path) && !DriveExists(path))
			MdThrowStringExceptionF(IDS_THEDIRECTORYsDOESNOTEXIST, path);
	}
	else
	{
		ASSERT(item->GetType() == IT_FILE);

		if (!FileExists(path))
			MdThrowStringExceptionF(IDS_THEFILEsDOESNOTEXIST, path);
	}

	if (udc->recurseIntoSubdirectories && item->GetType() != IT_FILESFOLDER)
	{
		ASSERT(item->GetType() == IT_DRIVE || item->GetType() == IT_DIRECTORY);

		RecursiveUserDefinedCleanup(udc, path, path);
	}
	else
	{
		CallUserDefinedCleanup(isDirectory, udc->commandLine, path, path, udc->showConsoleWindow, udc->waitForCompletion);
	}
}
예제 #2
0
bool ServiceUpdate(bool validService)
{
	if (validService)
	{
		ServiceInstaller si;

		if (si.run() != 0)
			return false;
	}
	else
	{
		std::wstring appPath = UTIL::OS::getCommonProgramFilesPath();

		if (!FolderExists(appPath.c_str()))
			CreateDirectoryW(appPath.c_str(), NULL);

		std::wstring newService = UTIL::OS::getCommonProgramFilesPath(L"desura_service.exe");
		std::wstring curService = UTIL::OS::getCurrentDir(L"desura_service.exe");

		char regname[255];
		Safe::snprintf(regname, 255, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\%s\\ImagePath", SERVICE_NAME);

		CopyFileW(curService.c_str(), newService.c_str(), FALSE);
		UTIL::WIN::setRegValue(regname, gcString(newService).c_str());
	}

	return true;
}
예제 #3
0
const bool OTPaths::PathExists(const OTString & strPath)
{
	if (!strPath.Exists()) { OTLog::sError("%s: Null: %s passed in!\n", __FUNCTION__, "strPath" ); OT_ASSERT(false); }


	// remove trailing backslash for stat
	std::string l_strPath(strPath.Get());
	l_strPath = (OTString::replace_chars(l_strPath,"\\",'/'));  // all \ to /

	//std::string l_strPath_stat = l_strPath;
	std::string l_strPath_stat("");
	
	// remove last / if it exists (for l_strPath_stat)
	if ('/' == *l_strPath.rbegin())
		l_strPath_stat = l_strPath.substr(0, l_strPath.size()-1);
	else l_strPath_stat = l_strPath;

	struct stat st; 
    memset(&st, 0, sizeof(st));
    
	if (0 == stat(l_strPath_stat.c_str(), &st)) // good we have at-least on a node
	{
		if ('/' != *l_strPath.rbegin())
		{
			long temp_l=0;
			return FileExists(strPath,temp_l);
		}
		else
		{
			return FolderExists(strPath);
		}
	}
	return false;
}
예제 #4
0
bool FileMisc::CreateFolder(const TCHAR* szFolder)
{
	if (FolderExists(szFolder))
	{
		return true;
	}

	// start from the highest level folder working to the lowest
	CString sFolder, sRemaining(szFolder);
	UnterminatePath(sRemaining);

	bool bDone = false;
	bool bResult = true;

	// pull off the :\ or \\ start
	int nFind = sRemaining.Find(_T(":\\"));

	if (nFind != -1)
	{
		sFolder += sRemaining.Left(nFind + 2);
		sRemaining = sRemaining.Mid(nFind + 2);
	}
	else
	{
		nFind = sRemaining.Find(_T("\\\\"));

		if (nFind != -1)
		{
			sFolder += sRemaining.Left(nFind + 2);
			sRemaining = sRemaining.Mid(nFind + 2);
		}
	}

	while (!bDone && bResult)
	{
		nFind = sRemaining.Find(_T('\\'), 1);

		if (nFind == -1)
		{
			bDone = TRUE;
			sFolder += sRemaining;
		}
		else
		{
			sFolder += sRemaining.Left(nFind);
			sRemaining = sRemaining.Mid(nFind);
		}

		if (GetFileAttributes(sFolder) == 0xffffffff && CreateDirectory(sFolder, NULL) != 0)
		{
			bResult = false;
		}
	}

	return bResult;
}
예제 #5
0
void CreateFolder(const char* path){	
	if(FolderExists(path)){
		return;
	}else{
		string s(path);
		string sep("\\");		
		string::iterator pos = std::find_end(s.begin(), s.end(), sep.begin(), sep.end());

		if (pos != s.end()){
			string s2(s.begin(), pos);
			//std::cout << s2 << std::endl;
			if (!FolderExists(s2.c_str())){
				CreateFolder(s2.c_str());
			}
			_mkdir(path);
		}
	}

}
예제 #6
0
bool FileMisc::RemoveFolder(const TCHAR* szFolder, HANDLE hTerminate, BOOL bProcessMsgLoop)
{
	// if the dir does not exists just return
	if (!FolderExists(szFolder))
	{
		return true;
	}

	if (DeleteFolderContents(szFolder, TRUE, NULL, hTerminate, bProcessMsgLoop))
	{
		::SetFileAttributes(szFolder, FILE_ATTRIBUTE_NORMAL);
		return (RemoveDirectory(szFolder) == TRUE);
	}

	return false;
}
예제 #7
0
CString FileMisc::GetFolderFromFilePath(const TCHAR* szFilePath)
{
	CString sFolder;

	// check if its a folder already
	if (FolderExists(szFilePath))
	{
		sFolder = szFilePath;
	}
	else
	{
		// remove file ending
		CString sDrive, sDir;

		SplitPath(szFilePath, &sDrive, &sDir);
		MakePath(sFolder, sDrive, sDir);
	}

	return sFolder;
}
예제 #8
0
// static
bool OTPaths::PathExists(const String& strPath)
{
    if (!strPath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strPath"
              << " passed in!\n";
        OT_FAIL;
    }

    // remove trailing backslash for stat
    std::string l_strPath(strPath.Get());
    l_strPath = (String::replace_chars(l_strPath, "\\", '/')); // all \ to /

    // std::string l_strPath_stat = l_strPath;
    std::string l_strPath_stat("");

    // remove last / if it exists (for l_strPath_stat)
    if ('/' == *l_strPath.rbegin())
        l_strPath_stat = l_strPath.substr(0, l_strPath.size() - 1);
    else
        l_strPath_stat = l_strPath;

    struct stat st;
    memset(&st, 0, sizeof(st));

    if (0 ==
        stat(l_strPath_stat.c_str(), &st)) // good we have at-least on a node
    {
        if ('/' != *l_strPath.rbegin()) {
            int64_t temp_l = 0;
            return FileExists(strPath, temp_l);
        }
        else {
            return FolderExists(strPath);
        }
    }
    return false;
}
예제 #9
0
bool FileMisc::CopyFolder(const TCHAR* szSrcFolder, const TCHAR* szDestFolder, BOOL bIncludeSubFolders,
	const TCHAR* szFileMask, HANDLE hTerminate, BOOL bProcessMsgLoop)
{
	if (!CreateFolder(szDestFolder))
	{
		return false;
	}

	if (!FolderExists(szSrcFolder))
	{
		return false;
	}

	// if a file mask has been specified with subfolders we need to do 2 passes on each folder,
	// one for the files and one for the sub folders
	int nPasses = (bIncludeSubFolders && (szFileMask && lstrlen(szFileMask))) ? 2 : 1;

	bool bResult = true;
	bool bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);

	for (int nPass = 0; !bStopped && nPass < nPasses; nPass++)
	{
		CString sSearchSpec(szSrcFolder), sMask(szFileMask);

		if (sMask.IsEmpty() || nPass == 1) // (nPass == 1) == 2nd pass (for folders)
		{
			sMask = "*.*";
		}

		TerminatePath(sSearchSpec);
		sSearchSpec += sMask;

		WIN32_FIND_DATA finfo;
		HANDLE hSearch = NULL;

		if ((hSearch = FindFirstFile(sSearchSpec, &finfo)) != INVALID_HANDLE_VALUE)
		{
			do
			{
				if (bProcessMsgLoop)
				{
					Misc::ProcessMsgLoop();
				}

				if (finfo.cFileName[0] != '.')
				{
					CString sSource(szSrcFolder);
					sSource += "\\";
					sSource += finfo.cFileName;

					CString sDest(szDestFolder);
					sDest += "\\";
					sDest += finfo.cFileName;

					if (finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					{
						if ((nPass == 1 || nPasses == 1) && bIncludeSubFolders)
						{
							bResult = CopyFolder(sSource, sDest, hTerminate);
						}
					}
					else if (nPass == 0) // files
					{
						bResult = (TRUE == CopyFile(sSource, sDest, FALSE));
					}
				}

				bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);
			}
			while (!bStopped && bResult && FindNextFile(hSearch, &finfo));

			FindClose(hSearch);
		}
	}

	return (!bStopped && bResult);
}
예제 #10
0
bool FileMisc::FolderFromFilePathExists(const TCHAR* szFilePath)
{
	return FolderExists(GetFolderFromFilePath(szFilePath));
}
예제 #11
0
double FileMisc::GetFolderSize(const TCHAR* szFolder, BOOL bIncludeSubFolders, const TCHAR* szFileMask,
	HANDLE hTerminate, BOOL bProcessMsgLoop)
{
	// if the dir does not exists just return
	if (!FolderExists(szFolder))
	{
		return 0;
	}

	double dSize = 0;

	WIN32_FIND_DATA finfo;
	CString sSearchSpec(szFolder), sFileMask(szFileMask);

	if (sFileMask.IsEmpty())
	{
		sFileMask = "*.*";
	}

	TerminatePath(sSearchSpec);
	sSearchSpec += sFileMask;

	BOOL bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);
	HANDLE h = NULL;

	if (!bStopped && (h = FindFirstFile(sSearchSpec, &finfo)) != INVALID_HANDLE_VALUE)
	{
		do
		{
			if (bProcessMsgLoop)
			{
				Misc::ProcessMsgLoop();
			}

			if (finfo.cFileName[0] != '.')
			{
				if (finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					if (bIncludeSubFolders)
					{
						CString sSubFolder(szFolder);
						sSubFolder += "\\";
						sSubFolder += finfo.cFileName;

						dSize += GetFolderSize(sSubFolder, TRUE, sFileMask, hTerminate, bProcessMsgLoop);
					}
				}
				else
				{
					dSize += (finfo.nFileSizeHigh * ((double)MAXDWORD + 1)) + finfo.nFileSizeLow;
				}
			}

			bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);
		}
		while (!bStopped && FindNextFile(h, &finfo));

		FindClose(h);
	}

	return bStopped ? -1 : dSize;
}
예제 #12
0
// Return: false if deleted
bool CItem::StartRefresh() 
{
	ASSERT(GetType() != IT_FREESPACE);
	ASSERT(GetType() != IT_UNKNOWN);

	m_ticksWorked = 0;

	// Special case IT_MYCOMPUTER
	if (GetType() == IT_MYCOMPUTER)
	{
		ZeroMemory(&m_lastChange, sizeof(m_lastChange));

		for (int i=0; i < GetChildrenCount(); i++)
			GetChild(i)->StartRefresh();

		return true;
	}
	ASSERT(GetType() == IT_FILE || GetType() == IT_DRIVE || GetType() == IT_DIRECTORY || GetType() == IT_FILESFOLDER);

	bool wasExpanded = IsVisible() && IsExpanded();
	int oldScrollPosition = 0;
	if (IsVisible())
		oldScrollPosition = GetScrollPosition();

	UncacheImage();

	// Upward clear data
	UpdateLastChange();

	UpwardSetUndone();

	UpwardAddReadJobs(-GetReadJobs());
	ASSERT(GetReadJobs() == 0);

	if (GetType() == IT_FILE)
		GetParent()->UpwardAddFiles(-1);
	else
		UpwardAddFiles(-GetFilesCount());
	ASSERT(GetFilesCount() == 0);

	if (GetType() == IT_DIRECTORY || GetType() == IT_DRIVE)
		UpwardAddSubdirs(-GetSubdirsCount());
	ASSERT(GetSubdirsCount() == 0);

	UpwardAddSize(-GetSize());
	ASSERT(GetSize() == 0);

	RemoveAllChildren();
	UpwardRecalcLastChange();

	// Special case IT_FILESFOLDER
	if (GetType() == IT_FILESFOLDER)
	{
		CFileFindWDS finder;
		BOOL b = finder.FindFile(GetFindPattern());
		while (b)
		{
			b = finder.FindNextFile();
			if (finder.IsDirectory())
				continue;

			FILEINFO fi;
			fi.name = finder.GetFileName();
			fi.attributes = finder.GetAttributes();
			// Retrieve file size
			fi.length = finder.GetCompressedLength();
			finder.GetLastWriteTime(&fi.lastWriteTime);

			AddFile(fi);
			UpwardAddFiles(1);
		}
		SetDone();

		if (wasExpanded)
			GetTreeListControl()->ExpandItem(this);
		return true;
	}
	ASSERT(GetType() == IT_FILE || GetType() == IT_DRIVE || GetType() == IT_DIRECTORY);

	// The item may have been deleted.
	bool deleted = false;
	if (GetType() == IT_DRIVE)
		deleted = !DriveExists(GetPath());
	else if (GetType() == IT_FILE)
		deleted = !FileExists(GetPath());
	else if (GetType() == IT_DIRECTORY)
		deleted = !FolderExists(GetPath());

	if (deleted)
	{
		if (GetParent() == NULL)
		{
			GetDocument()->UnlinkRoot();
		}
		else
		{
			GetParent()->UpwardRecalcLastChange();
			GetParent()->RemoveChild(GetParent()->FindChildIndex(this)); // --> delete this
		}
		return false;
	}

	// Case IT_FILE
	if (GetType() == IT_FILE)
	{
		CFileFindWDS finder;
		BOOL b = finder.FindFile(GetPath());
		if (b)
		{
			finder.FindNextFile();
			if (!finder.IsDirectory())
			{
				FILEINFO fi;
				fi.name = finder.GetFileName();
				fi.attributes = finder.GetAttributes();
				// Retrieve file size
				fi.length = finder.GetCompressedLength();
				finder.GetLastWriteTime(&fi.lastWriteTime);

				SetLastChange(fi.lastWriteTime);

				UpwardAddSize(fi.length);
				UpwardUpdateLastChange(GetLastChange());
				GetParent()->UpwardAddFiles(1);
			}
		}
		SetDone();
		return true;
	}

	ASSERT(GetType() == IT_DRIVE || GetType() == IT_DIRECTORY);

	if (GetType() == IT_DIRECTORY && !IsRootItem() && GetApp()->IsMountPoint(GetPath()) && !GetOptions()->IsFollowMountPoints())
		return true;

	if (GetType() == IT_DIRECTORY && !IsRootItem() && GetApp()->IsJunctionPoint(GetPath()) && !GetOptions()->IsFollowJunctionPoints())
		return true;

	// Initiate re-read
	SetReadJobDone(false);

	// Re-create <free space> and <unknown>
	if (GetType() == IT_DRIVE)
	{
		if (GetDocument()->OptionShowFreeSpace())
			CreateFreeSpaceItem();
		if (GetDocument()->OptionShowUnknown())
			CreateUnknownItem();
	}

	DoSomeWork(0);

	if (wasExpanded)
		GetTreeListControl()->ExpandItem(this);

	if (IsVisible())
		SetScrollPosition(oldScrollPosition);

	return true;
}
예제 #13
0
BOOL OnNotify(HWND hDlg, LPNMHDR lpNMHdr)
{
    //DEBUGMESSAGE(("OnNotify"));

    UINT uiCode = lpNMHdr->code;
    switch (uiCode)
    {
    case PSN_APPLY:
        {
            DEBUGMESSAGE(("OnNotify - PSN_APPLY"));

            DocumentPropDialogData *data = 
                (DocumentPropDialogData *) GetWindowLongPtr(hDlg, DWL_USER);
            if (data == NULL) {
                DEBUGMESSAGE(("DocPropDlgProc - invalid internal data pointer"));
                return FALSE;
            }

            // which format combo should we use?
            LPTSTR format = NULL;
            if (IsDlgButtonChecked(hDlg, IDC_VECTOR_FORMAT_RADIOBOX) == BST_CHECKED)
            {
                INT sel = GetComboCurSel(GetDlgItem(hDlg, IDC_COMBO_VECTOR_FORMAT));
                format = strDuplicate(g_vectorFormats[sel].strName);
            }
            else if (IsDlgButtonChecked(hDlg, IDC_RASTER_FORMAT_RADIOBOX) == BST_CHECKED)
            {
                INT sel = GetComboCurSel(GetDlgItem(hDlg, IDC_COMBO_RASTER_FORMAT));
                format = strDuplicate(g_rasterFormats[sel].strName);
            }
            else
            {
                DEBUGMESSAGE(("DocPropDlgProc - unexpected condition"));
                return FALSE;
            }

            // get the output folder & validate it
            LPTSTR folder = NULL;
            if (!GetEditControlText(&folder, GetDlgItem(hDlg, IDC_OUTPUT_FOLDER))) {
                DEBUGMESSAGE(("DocPropDlgProc - could not get output folder text"));
                return FALSE;
            }
            if (!FolderExists(folder)) {
                ErrorMessage(hDlg, TEXT("Warning"),
                       TEXT("The given output directory does not exist!"));
                return FALSE;
            }

            // get the output filename & validate it
            LPTSTR filename = NULL;
            if (!GetEditControlText(&filename, GetDlgItem(hDlg, IDC_OUTPUT_FILENAME))) {
                DEBUGMESSAGE(("DocPropDlgProc - could not get output filename text"));
                return FALSE;
            }
            if (!IsValidFilename(filename)) {
                LPTSTR temp = strCat(TEXT("The given output filename is not valid!\n"),
                                     TEXT("It should not contain any of the '"),
                                     g_strFileNameForbiddenChars,
                                     TEXT("' characters."),
                                     NULL);
                ErrorMessage(hDlg, TEXT("Warning"), temp);
                strFree(temp);
                return FALSE;
            }

            // get the raster conv options
            LPTSTR rasteropt = NULL;
            if (!GetEditControlText(&rasteropt, GetDlgItem(hDlg, IDC_IMAGEMAGICK_OPTIONS))) {
                DEBUGMESSAGE(("DocPropDlgProc - could not get raster conv opt text"));
                return FALSE;
            }

            // get the postgen cmd
            LPTSTR postgen = NULL;
            if (!GetEditControlText(&postgen, GetDlgItem(hDlg, IDC_POSTGEN_CMD))) {
                DEBUGMESSAGE(("DocPropDlgProc - could not get postgen cmd text"));
                return FALSE;
            }

            // get override checkbox status
            BOOL override = 
                IsDlgButtonChecked(hDlg, IDC_OVERRIDE_CHECKBOX) == BST_CHECKED;

            // get crop checkbox
            BOOL crop = 
                IsDlgButtonChecked(hDlg, IDC_CROP_CHECKBOX) == BST_CHECKED;

            // get open-output checkbox
            BOOL openout = 
                IsDlgButtonChecked(hDlg, IDC_OPEN_VIEWER_CHECKBOX) == BST_CHECKED;

            // save all data in the EXTDEVMODE
            extdmSetPrivateData(data->m_pExtdmCurrent, 
                                format, filename, folder, rasteropt, postgen, 
                                override, openout, crop);

            // cleanup
            strFree(format);  
            strFree(filename);  
            strFree(folder);
            strFree(postgen);
            strFree(rasteropt);

            // call the _SET_RESULT callback
            PFNCOMPROPSHEET pfnComPropSheet = data->m_pfnComPropSheet;
            LONG lTemp = pfnComPropSheet(
                                        data->m_hComPropSheet, 
                                        CPSFUNC_SET_RESULT,
                                        (LPARAM) data->m_hPropSheetAdded,
                                        CPSUI_OK
                                        );

            return TRUE;
        }
        break;

    case PSN_RESET:
        break;

    case PSN_SETACTIVE:
        break;

    default:
        break;
    }

    return FALSE;
}
예제 #14
0
int
main(int argc, char **argv)
{
  nsresult rv;
  char *lastSlash;

  char iniPath[MAXPATHLEN];
  char tmpPath[MAXPATHLEN];
  char greDir[MAXPATHLEN];
  PRBool greFound = PR_FALSE;

#if defined(XP_MACOSX)
  CFBundleRef appBundle = CFBundleGetMainBundle();
  if (!appBundle)
    return 1;

  CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(appBundle);
  if (!resourcesURL)
    return 1;

  CFURLRef absResourcesURL = CFURLCopyAbsoluteURL(resourcesURL);
  CFRelease(resourcesURL);
  if (!absResourcesURL)
    return 1;

  CFURLRef iniFileURL =
    CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault,
                                          absResourcesURL,
                                          CFSTR("application.ini"),
                                          false);
  CFRelease(absResourcesURL);
  if (!iniFileURL)
    return 1;

  CFStringRef iniPathStr =
    CFURLCopyFileSystemPath(iniFileURL, kCFURLPOSIXPathStyle);
  CFRelease(iniFileURL);
  if (!iniPathStr)
    return 1;

  CFStringGetCString(iniPathStr, iniPath, sizeof(iniPath),
                     kCFStringEncodingUTF8);
  CFRelease(iniPathStr);

#else

#ifdef XP_WIN
  wchar_t wide_path[MAX_PATH];
  if (!::GetModuleFileNameW(NULL, wide_path, MAX_PATH))
    return 1;

  WideCharToMultiByte(CP_UTF8, 0, wide_path,-1,
		      iniPath, MAX_PATH, NULL, NULL);

#elif defined(XP_OS2)
   PPIB ppib;
   PTIB ptib;

   DosGetInfoBlocks(&ptib, &ppib);
   DosQueryModuleName(ppib->pib_hmte, sizeof(iniPath), iniPath);

#elif defined(XP_BEOS)
   BEntry e((const char *)argv[0], true); // traverse symlink
   BPath p;
   status_t err;
   err = e.GetPath(&p);
   NS_ASSERTION(err == B_OK, "realpath failed");

   if (err == B_OK)
     // p.Path returns a pointer, so use strcpy to store path in iniPath
     strcpy(iniPath, p.Path());

#else
  // on unix, there is no official way to get the path of the current binary.
  // instead of using the MOZILLA_FIVE_HOME hack, which doesn't scale to
  // multiple applications, we will try a series of techniques:
  //
  // 1) use realpath() on argv[0], which works unless we're loaded from the
  //    PATH
  // 2) manually walk through the PATH and look for ourself
  // 3) give up

  struct stat fileStat;

  if (!realpath(argv[0], iniPath) || stat(iniPath, &fileStat)) {
    const char *path = getenv("PATH");
    if (!path)
      return 1;

    char *pathdup = strdup(path);
    if (!pathdup)
      return 1;

    PRBool found = PR_FALSE;
    char *token = strtok(pathdup, ":");
    while (token) {
      sprintf(tmpPath, "%s/%s", token, argv[0]);
      if (realpath(tmpPath, iniPath) && stat(iniPath, &fileStat) == 0) {
        found = PR_TRUE;
        break;
      }
      token = strtok(NULL, ":");
    }
    free (pathdup);
    if (!found)
      return 1;
  }
#endif

  lastSlash = strrchr(iniPath, PATH_SEPARATOR_CHAR);
  if (!lastSlash)
    return 1;

  *(++lastSlash) = '\0';

  // On Linux/Win, look for XULRunner in appdir/xulrunner

  snprintf(greDir, sizeof(greDir),
           "%sxulrunner" XPCOM_FILE_PATH_SEPARATOR XPCOM_DLL,
           iniPath);

  greFound = FolderExists(greDir);

  strncpy(lastSlash, "application.ini", sizeof(iniPath) - (lastSlash - iniPath));

#endif

  // If -app parameter was passed in, it is now time to take it under 
  // consideration.
  const char *appDataFile;
  appDataFile = getenv("XUL_APP_FILE");
  if (!appDataFile || !*appDataFile) 
    if (argc > 1 && IsArg(argv[1], "app")) {
      if (argc == 2) {
        Output(PR_FALSE, "specify APP-FILE (optional)\n");
        return 1;
      }
      argv[1] = argv[0];
      ++argv;
      --argc;

      appDataFile = argv[1];
      argv[1] = argv[0];
      ++argv;
      --argc;

      char kAppEnv[MAXPATHLEN];
      snprintf(kAppEnv, MAXPATHLEN, "XUL_APP_FILE=%s", appDataFile);
      if (putenv(kAppEnv)) 
        Output(PR_FALSE, "Couldn't set %s.\n", kAppEnv);

      char *result = (char*) calloc(sizeof(char), MAXPATHLEN);
      if (NS_FAILED(GetRealPath(appDataFile, &result))) {
        Output(PR_TRUE, "Invalid application.ini path.\n");
        return 1;
      }
      
      // We have a valid application.ini path passed in to the -app parameter 
      // but not yet a valid greDir, so lets look for it also on the same folder
      // as the stub.
      if (!greFound) {
        lastSlash = strrchr(iniPath, PATH_SEPARATOR_CHAR);
        if (!lastSlash)
          return 1;

        *(++lastSlash) = '\0';

        snprintf(greDir, sizeof(greDir), "%s" XPCOM_DLL, iniPath);
        greFound = FolderExists(greDir);
      }
      
      // copy it back.
      strcpy(iniPath, result);
    }
  
  nsINIParser parser;
  rv = parser.Init(iniPath);
  if (NS_FAILED(rv)) {
    fprintf(stderr, "Could not read application.ini\n");
    return 1;
  }

#ifdef WINCE
  // On Windows Mobile and WinCE, we can save a lot of time by not
  // waiting for XUL and XPCOM to load up.  Let's see if we can find
  // an existing app window to forward our command-line to now.

  // Shouldn't attempt this if the -no-remote parameter has been provided.
  bool noRemote = false;
  for (int i = 1; i < argc; i++) {
    if (IsArg(argv[i], "no-remote")) {
      noRemote = true;
      break;
    }
  }

  if (!noRemote) {
    char windowName[512];  // Is there a const for appname like VERSION_MAXLEN?
    rv = parser.GetString("App", "Name", windowName, sizeof(windowName));
    if (NS_FAILED(rv)) {
      fprintf(stderr, "Couldn't figure out the application name\n");
      return 1;
    }

    // Lookup the hidden message window created by nsNativeAppSupport
    strncat(windowName, "MessageWindow", sizeof(windowName) - strlen(windowName));
    WCHAR wWindowName[512];
    MultiByteToWideChar(CP_UTF8, 0, windowName, -1, wWindowName, sizeof(wWindowName));
    HWND wnd = ::FindWindowW(wWindowName, NULL);
    if (wnd) {
      // Forward the command-line and bail out
      ForwardToWindow(wnd);
      return 0;
    }
  }
#endif

  if (!greFound) {
    char minVersion[VERSION_MAXLEN];

    // If a gecko maxVersion is not specified, we assume that the app uses only
    // frozen APIs, and is therefore compatible with any xulrunner 1.x.
    char maxVersion[VERSION_MAXLEN] = "1.*";

    GREVersionRange range = {
      minVersion,
      PR_TRUE,
      maxVersion,
      PR_TRUE
    };

    rv = parser.GetString("Gecko", "MinVersion", minVersion, sizeof(minVersion));
    if (NS_FAILED(rv)) {
      fprintf(stderr,
              "The application.ini does not specify a [Gecko] MinVersion\n");
      return 1;
    }

    rv = parser.GetString("Gecko", "MaxVersion", maxVersion, sizeof(maxVersion));
    if (NS_SUCCEEDED(rv))
      range.upperInclusive = PR_TRUE;

    static const GREProperty kProperties[] = {
      { "xulrunner", "true" }
    };

    rv = GRE_GetGREPathWithProperties(&range, 1,
                                      kProperties, NS_ARRAY_LENGTH(kProperties),
                                      greDir, sizeof(greDir));
    if (NS_FAILED(rv)) {
      // XXXbsmedberg: Do something much smarter here: notify the
      // user/offer to download/?

      Output(PR_FALSE,
             "Could not find compatible GRE between version %s and %s.\n",
             range.lower, range.upper);
      return 1;
    }
#ifdef XP_UNIX
    // Using a symlinked greDir will fail during startup. Not sure why, but if
    // we resolve the symlink, everything works as expected.
    char resolved_greDir[MAXPATHLEN] = "";  
    if (realpath(greDir, resolved_greDir) && *resolved_greDir) {
      strncpy(greDir, resolved_greDir, MAXPATHLEN);
    }
#endif
  }

#ifdef XP_OS2
  // On OS/2 we need to set BEGINLIBPATH to be able to find XULRunner DLLs
  strcpy(tmpPath, greDir);
  lastSlash = strrchr(tmpPath, PATH_SEPARATOR_CHAR);
  if (lastSlash) {
    *lastSlash = '\0';
  }
  DosSetExtLIBPATH(tmpPath, BEGIN_LIBPATH);
#endif

  rv = XPCOMGlueStartup(greDir);
  if (NS_FAILED(rv)) {
    if (rv == NS_ERROR_OUT_OF_MEMORY) {
      char applicationName[2000] = "this application";
      parser.GetString("App", "Name", applicationName, sizeof(applicationName));
      Output(PR_TRUE, "Not enough memory available to start %s.\n",
             applicationName);
    } else {
      Output(PR_TRUE, "Couldn't load XPCOM.\n");
    }
    return 1;
  }

  static const nsDynamicFunctionLoad kXULFuncs[] = {
    { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData },
    { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData },
    { "XRE_main", (NSFuncPtr*) &XRE_main },
    { nsnull, nsnull }
  };

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output(PR_TRUE, "Couldn't load XRE functions.\n");
    return 1;
  }

  NS_LogInit();

  int retval;

  { // Scope COMPtr and AutoAppData
    nsCOMPtr<nsILocalFile> iniFile;
#ifdef XP_WIN
    // On Windows and Windows CE, iniPath is UTF-8 encoded,
    // so we need to convert it.
    rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(iniPath), PR_FALSE,
                         getter_AddRefs(iniFile));
#else
    rv = NS_NewNativeLocalFile(nsDependentCString(iniPath), PR_FALSE,
                               getter_AddRefs(iniFile));
#endif
    if (NS_FAILED(rv)) {
      Output(PR_TRUE, "Couldn't find application.ini file.\n");
      return 1;
    }

    AutoAppData appData(iniFile);
    if (!appData) {
      Output(PR_TRUE, "Error: couldn't parse application.ini.\n");
      return 1;
    }

    NS_ASSERTION(appData->directory, "Failed to get app directory.");

    if (!appData->xreDirectory) {
      // chop "libxul.so" off the GRE path
      lastSlash = strrchr(greDir, PATH_SEPARATOR_CHAR);
      if (lastSlash) {
        *lastSlash = '\0';
      }
#ifdef XP_WIN
      // same as iniPath.
      NS_NewLocalFile(NS_ConvertUTF8toUTF16(greDir), PR_FALSE,
                      &appData->xreDirectory);
#else
      NS_NewNativeLocalFile(nsDependentCString(greDir), PR_FALSE,
                            &appData->xreDirectory);
#endif
    }

    retval = XRE_main(argc, argv, appData);
  }

  NS_LogTerm();

  XPCOMGlueShutdown();

  return retval;
}
예제 #15
0
bool FileMisc::DeleteFolderContents(const TCHAR* szFolder, BOOL bIncludeSubFolders, const TCHAR* szFileMask,
	HANDLE hTerminate, BOOL bProcessMsgLoop)
{
	// if the dir does not exists just return
	if (!FolderExists(szFolder))
	{
		return true;
	}

	// if a file mask has been specified with subfolders we need to do 2 passes on each folder,
	// one for the files and one for the sub folders
	int nPasses = (bIncludeSubFolders && (szFileMask && lstrlen(szFileMask))) ? 2 : 1;

	bool bResult = true;
	bool bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);

	for (int nPass = 0; !bStopped && nPass < nPasses; nPass++)
	{
		CString sSearchSpec(szFolder), sMask(szFileMask);

		if (sMask.IsEmpty() || nPass == 1) // (nPass == 1) == 2nd pass (for folders)
		{
			sMask = "*.*";
		}

		TerminatePath(sSearchSpec);
		sSearchSpec += sMask;

		WIN32_FIND_DATA finfo;
		HANDLE hSearch = NULL;

		if ((hSearch = FindFirstFile(sSearchSpec, &finfo)) != INVALID_HANDLE_VALUE)
		{
			do
			{
				if (bProcessMsgLoop)
				{
					Misc::ProcessMsgLoop();
				}

				if (finfo.cFileName[0] != '.')
				{
					CString sItem(szFolder);
					sItem += "\\";
					sItem += finfo.cFileName;

					if (finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					{
						if (bIncludeSubFolders && (nPass == 1 || nPasses == 1))
						{
							if (DeleteFolderContents(sItem, TRUE, szFileMask, hTerminate, bProcessMsgLoop))
							{
								if (!szFileMask || !lstrlen(szFileMask))
								{
									bResult = (RemoveDirectory(sItem) == TRUE);
								}
							}
						}
					}
					else
					{
						bResult = (DeleteFile(sItem) == TRUE);
					}
				}

				bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);
			}
			while (!bStopped && bResult && FindNextFile(hSearch, &finfo));

			FindClose(hSearch);
		}
	}

	return (!bStopped && bResult);
}
예제 #16
0
파일: push.c 프로젝트: Volkanite/Push
VOID Cache( PUSH_GAME* Game )
{
    CHAR mountPoint = 0;
    UINT64 bytes = 0, availableMemory = 0; // in bytes
    SYSTEM_BASIC_PERFORMANCE_INFORMATION performanceInfo;
    //BfBatchFile batchFile(Game);

    // Check if game is already cached so we donot have wait through another
    if (String_Compare(g_szPrevGame, Game->InstallPath) == 0 && !g_bRecache)
        return;

    g_bRecache = FALSE;

    if (!FolderExists(Game->InstallPath))
    {
        Log(L"Folder not exist!");
    }

    // Check available memory
    NtQuerySystemInformation(
        SystemBasicPerformanceInformation,
        &performanceInfo,
        sizeof(SYSTEM_BASIC_PERFORMANCE_INFORMATION),
        NULL
        );

    availableMemory = performanceInfo.AvailablePages * HwInfoSystemBasicInformation.PageSize;

    // Read batch file
    PushFileList = 0;

    BatchFile_Initialize(Game);
    bytes = BatchFile_GetBatchSize();
    PushFileList = BatchFile_GetBatchList();

    // Check if any files at all are marked for cache, if not return.
    if (PushFileList == NULL)
        // List is empty hence no files to cache, return.
        return;

    // Add 200MB padding for disk format;
    bytes += 209715200;

    if (bytes > availableMemory)
    {
        MessageBoxW(
            NULL,
            L"There isn't enough memory to hold all the files you marked for caching.\n"
            L"The Ramdisk will be set to an acceptable size and filled with what it can hold.\n"
            L"Please upgrade RAM.",
            L"Push",
            MB_TOPMOST
            );
    }

    RemoveRamDisk();

    mountPoint = FindFreeDriveLetter();

    CreateRamDisk(bytes, mountPoint);
    FormatRamDisk();
    CacheFiles(mountPoint);

    // Release batchfile list
    PushFileList = NULL;

    String_Copy(g_szPrevGame, Game->InstallPath);
}
예제 #17
0
int
main(int argc, char **argv)
{
  nsresult rv;
  char *lastSlash;

  char iniPath[MAXPATHLEN];
  char tmpPath[MAXPATHLEN];
  char greDir[MAXPATHLEN];
  bool greFound = false;

#if defined(XP_MACOSX)
  CFBundleRef appBundle = CFBundleGetMainBundle();
  if (!appBundle)
    return 1;

  CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(appBundle);
  if (!resourcesURL)
    return 1;

  CFURLRef absResourcesURL = CFURLCopyAbsoluteURL(resourcesURL);
  CFRelease(resourcesURL);
  if (!absResourcesURL)
    return 1;

  CFURLRef iniFileURL =
    CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault,
                                          absResourcesURL,
                                          CFSTR("application.ini"),
                                          false);
  CFRelease(absResourcesURL);
  if (!iniFileURL)
    return 1;

  CFStringRef iniPathStr =
    CFURLCopyFileSystemPath(iniFileURL, kCFURLPOSIXPathStyle);
  CFRelease(iniFileURL);
  if (!iniPathStr)
    return 1;

  CFStringGetCString(iniPathStr, iniPath, sizeof(iniPath),
                     kCFStringEncodingUTF8);
  CFRelease(iniPathStr);

#else

#ifdef XP_WIN
  wchar_t wide_path[MAX_PATH];
  if (!::GetModuleFileNameW(NULL, wide_path, MAX_PATH))
    return 1;

  WideCharToMultiByte(CP_UTF8, 0, wide_path,-1,
		      iniPath, MAX_PATH, NULL, NULL);

#elif defined(XP_OS2)
   PPIB ppib;
   PTIB ptib;

   DosGetInfoBlocks(&ptib, &ppib);
   DosQueryModuleName(ppib->pib_hmte, sizeof(iniPath), iniPath);

#else
  // on unix, there is no official way to get the path of the current binary.
  // instead of using the MOZILLA_FIVE_HOME hack, which doesn't scale to
  // multiple applications, we will try a series of techniques:
  //
  // 1) use realpath() on argv[0], which works unless we're loaded from the
  //    PATH
  // 2) manually walk through the PATH and look for ourself
  // 3) give up

  struct stat fileStat;
  strncpy(tmpPath, argv[0], sizeof(tmpPath));
  lastSlash = strrchr(tmpPath, '/');
  if (lastSlash) {
    *lastSlash = 0;
    realpath(tmpPath, iniPath);
  } else {
    const char *path = getenv("PATH");
    if (!path)
      return 1;

    char *pathdup = strdup(path);
    if (!pathdup)
      return 1;

    bool found = false;
    char *token = strtok(pathdup, ":");
    while (token) {
      sprintf(tmpPath, "%s/%s", token, argv[0]);
      if (stat(tmpPath, &fileStat) == 0) {
        found = true;
        lastSlash = strrchr(tmpPath, '/');
        *lastSlash = 0;
        realpath(tmpPath, iniPath);
        break;
      }
      token = strtok(NULL, ":");
    }
    free (pathdup);
    if (!found)
      return 1;
  }
  lastSlash = iniPath + strlen(iniPath);
  *lastSlash = '/';
#endif

#ifndef XP_UNIX
  lastSlash = strrchr(iniPath, PATH_SEPARATOR_CHAR);
  if (!lastSlash)
    return 1;
#endif

  *(++lastSlash) = '\0';

  // On Linux/Win, look for XULRunner in appdir/xulrunner

  snprintf(greDir, sizeof(greDir),
           "%sxulrunner" XPCOM_FILE_PATH_SEPARATOR XPCOM_DLL,
           iniPath);

  greFound = FolderExists(greDir);

#ifdef XP_UNIX
  if (greFound) {
    char resolved_greDir[MAXPATHLEN] = "";
    if (realpath(greDir, resolved_greDir) && *resolved_greDir) {
      strncpy(greDir, resolved_greDir, MAXPATHLEN);
    }
  }
#endif

  strncpy(lastSlash, "application.ini", sizeof(iniPath) - (lastSlash - iniPath));

#endif

  // If -app parameter was passed in, it is now time to take it under 
  // consideration.
  const char *appDataFile;
  appDataFile = getenv("XUL_APP_FILE");
  if (!appDataFile || !*appDataFile) 
    if (argc > 1 && IsArg(argv[1], "app")) {
      if (argc == 2) {
        Output(false, "specify APP-FILE (optional)\n");
        return 1;
      }
      argv[1] = argv[0];
      ++argv;
      --argc;

      appDataFile = argv[1];
      argv[1] = argv[0];
      ++argv;
      --argc;

      char kAppEnv[MAXPATHLEN];
      snprintf(kAppEnv, MAXPATHLEN, "XUL_APP_FILE=%s", appDataFile);
      if (putenv(kAppEnv)) 
        Output(false, "Couldn't set %s.\n", kAppEnv);

      char *result = (char*) calloc(sizeof(char), MAXPATHLEN);
      if (NS_FAILED(GetRealPath(appDataFile, &result))) {
        Output(true, "Invalid application.ini path.\n");
        return 1;
      }
      
      // We have a valid application.ini path passed in to the -app parameter 
      // but not yet a valid greDir, so lets look for it also on the same folder
      // as the stub.
      if (!greFound) {
        lastSlash = strrchr(iniPath, PATH_SEPARATOR_CHAR);
        if (!lastSlash)
          return 1;

        *(++lastSlash) = '\0';

        snprintf(greDir, sizeof(greDir), "%s" XPCOM_DLL, iniPath);
        greFound = FolderExists(greDir);
      }
      
      // copy it back.
      strcpy(iniPath, result);
    }
  
  nsINIParser parser;
  rv = parser.Init(iniPath);
  if (NS_FAILED(rv)) {
    fprintf(stderr, "Could not read application.ini\n");
    return 1;
  }

  if (!greFound) {
#ifdef XP_MACOSX
    // Check for <bundle>/Contents/Frameworks/XUL.framework/libxpcom.dylib
    CFURLRef fwurl = CFBundleCopyPrivateFrameworksURL(appBundle);
    CFURLRef absfwurl = nullptr;
    if (fwurl) {
      absfwurl = CFURLCopyAbsoluteURL(fwurl);
      CFRelease(fwurl);
    }

    if (absfwurl) {
      CFURLRef xulurl =
        CFURLCreateCopyAppendingPathComponent(NULL, absfwurl,
                                              CFSTR("XUL.framework"),
                                              true);

      if (xulurl) {
        CFURLRef xpcomurl =
          CFURLCreateCopyAppendingPathComponent(NULL, xulurl,
                                                CFSTR("libxpcom.dylib"),
                                                false);

        if (xpcomurl) {
          char tbuffer[MAXPATHLEN];

          if (CFURLGetFileSystemRepresentation(xpcomurl, true,
                                               (UInt8*) tbuffer,
                                               sizeof(tbuffer)) &&
              access(tbuffer, R_OK | X_OK) == 0) {
            if (realpath(tbuffer, greDir)) {
              greFound = true;
            }
            else {
              greDir[0] = '\0';
            }
          }

          CFRelease(xpcomurl);
        }

        CFRelease(xulurl);
      }

      CFRelease(absfwurl);
    }
#endif
    if (!greFound) {
      Output(false, "Could not find the Mozilla runtime.\n");
      return 1;
    }
  }

#ifdef XP_OS2
  // On OS/2 we need to set BEGINLIBPATH to be able to find XULRunner DLLs
  strcpy(tmpPath, greDir);
  lastSlash = strrchr(tmpPath, PATH_SEPARATOR_CHAR);
  if (lastSlash) {
    *lastSlash = '\0';
  }
  DosSetExtLIBPATH(tmpPath, BEGIN_LIBPATH);
#endif
  
  rv = XPCOMGlueStartup(greDir);
  if (NS_FAILED(rv)) {
    if (rv == NS_ERROR_OUT_OF_MEMORY) {
      char applicationName[2000] = "this application";
      parser.GetString("App", "Name", applicationName, sizeof(applicationName));
      Output(true, "Not enough memory available to start %s.\n",
             applicationName);
    } else {
      Output(true, "Couldn't load XPCOM.\n");
    }
    return 1;
  }

  static const nsDynamicFunctionLoad kXULFuncs[] = {
    { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData },
    { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData },
    { "XRE_main", (NSFuncPtr*) &XRE_main },
    { nullptr, nullptr }
  };

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output(true, "Couldn't load XRE functions.\n");
    return 1;
  }

  NS_LogInit();

  int retval;

  { // Scope COMPtr and AutoAppData
    nsCOMPtr<nsIFile> iniFile;
#ifdef XP_WIN
    // On Windows iniPath is UTF-8 encoded so we need to convert it.
    rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(iniPath), false,
                         getter_AddRefs(iniFile));
#else
    rv = NS_NewNativeLocalFile(nsDependentCString(iniPath), false,
                               getter_AddRefs(iniFile));
#endif
    if (NS_FAILED(rv)) {
      Output(true, "Couldn't find application.ini file.\n");
      return 1;
    }

    AutoAppData appData(iniFile);
    if (!appData) {
      Output(true, "Error: couldn't parse application.ini.\n");
      return 1;
    }

    NS_ASSERTION(appData->directory, "Failed to get app directory.");

    if (!appData->xreDirectory) {
      // chop "libxul.so" off the GRE path
      lastSlash = strrchr(greDir, PATH_SEPARATOR_CHAR);
      if (lastSlash) {
        *lastSlash = '\0';
      }
#ifdef XP_WIN
      // same as iniPath.
      NS_NewLocalFile(NS_ConvertUTF8toUTF16(greDir), false,
                      &appData->xreDirectory);
#else
      NS_NewNativeLocalFile(nsDependentCString(greDir), false,
                            &appData->xreDirectory);
#endif
    }

    retval = XRE_main(argc, argv, appData, 0);
  }

  NS_LogTerm();

  return retval;
}