virtual void run() {
		getFileInfo(gamePath_.c_str(), &info_->fileInfo);
		if (!info_->fileInfo.exists)
			return;

		std::string filename = gamePath_;
		info_->fileType = Identify_File(filename);

		switch (info_->fileType) {
		case FILETYPE_PSP_PBP:
		case FILETYPE_PSP_PBP_DIRECTORY:
			{
				std::string pbpFile = filename;
				if (info_->fileType == FILETYPE_PSP_PBP_DIRECTORY)
					pbpFile += "/EBOOT.PBP";

				PBPReader pbp(pbpFile.c_str());
				if (!pbp.IsValid())
					return;

				// First, PARAM.SFO.
				size_t sfoSize;
				u8 *sfoData = pbp.GetSubFile(PBP_PARAM_SFO, &sfoSize);
				{
					lock_guard lock(info_->lock);
					info_->paramSFO.ReadSFO(sfoData, sfoSize);
					info_->title = info_->paramSFO.GetValueString("TITLE");
					info_->id = info_->paramSFO.GetValueString("DISC_ID");
					info_->id_version = info_->paramSFO.GetValueString("DISC_ID") + "_" + info_->paramSFO.GetValueString("DISC_VERSION");
					info_->disc_total = info_->paramSFO.GetValueInt("DISC_TOTAL");
					info_->disc_number = info_->paramSFO.GetValueInt("DISC_NUMBER");

					info_->paramSFOLoaded = true;
				}
				delete [] sfoData;

				// Then, ICON0.PNG.
				{
					lock_guard lock(info_->lock);
					if (pbp.GetSubFileSize(PBP_ICON0_PNG) > 0) {
						pbp.GetSubFileAsString(PBP_ICON0_PNG, &info_->iconTextureData);
					} else {
						// Read standard icon
						size_t sz;
						DEBUG_LOG(LOADER, "Loading unknown.png because a PBP was missing an icon");
						uint8_t *contents = VFSReadFile("unknown.png", &sz);
						if (contents) {
							lock_guard lock(info_->lock);
							info_->iconTextureData = std::string((const char *)contents, sz);
						}
						delete [] contents;
					}
				}

				if (info_->wantBG) {
					if (pbp.GetSubFileSize(PBP_PIC1_PNG) > 0) {
						lock_guard lock(info_->lock);
						pbp.GetSubFileAsString(PBP_PIC1_PNG, &info_->pic1TextureData);
					}
				}
			}
			break;

		case FILETYPE_PSP_ELF:
			// An elf on its own has no usable information, no icons, no nothing.
			info_->title = getFilename(filename);
			info_->id = "ELF000000";
			info_->id_version = "ELF000000_1.00";
			info_->paramSFOLoaded = true;

			{
				// Read standard icon
				size_t sz;
				uint8_t *contents = VFSReadFile("unknown.png", &sz);
				DEBUG_LOG(LOADER, "Loading unknown.png because there was an ELF");
				if (contents) {
					lock_guard lock(info_->lock);
					info_->iconTextureData = std::string((const char *)contents, sz);
				}
				delete [] contents;
			}

			break;

		case FILETYPE_PSP_DISC_DIRECTORY:
			{
				info_->fileType = FILETYPE_PSP_ISO;
				SequentialHandleAllocator handles;
				VirtualDiscFileSystem umd(&handles,gamePath_.c_str());
				
				// Alright, let's fetch the PARAM.SFO.
				std::string paramSFOcontents;
				if (ReadFileToString(&umd, "/PSP_GAME/PARAM.SFO", &paramSFOcontents, 0)) {
					lock_guard lock(info_->lock);
					info_->paramSFO.ReadSFO((const u8 *)paramSFOcontents.data(), paramSFOcontents.size());
					info_->title = info_->paramSFO.GetValueString("TITLE");
					info_->id = info_->paramSFO.GetValueString("DISC_ID");
					info_->id_version = info_->paramSFO.GetValueString("DISC_ID") + "_" + info_->paramSFO.GetValueString("DISC_VERSION");
					info_->disc_total = info_->paramSFO.GetValueInt("DISC_TOTAL");
					info_->disc_number = info_->paramSFO.GetValueInt("DISC_NUMBER");

					info_->paramSFOLoaded = true;
				}

				ReadFileToString(&umd, "/PSP_GAME/ICON0.PNG", &info_->iconTextureData, &info_->lock);
				if (info_->wantBG) {
					ReadFileToString(&umd, "/PSP_GAME/PIC0.PNG", &info_->pic0TextureData, &info_->lock);
				}
				ReadFileToString(&umd, "/PSP_GAME/PIC1.PNG", &info_->pic1TextureData, &info_->lock);
				break;
			}
		case FILETYPE_PSP_ISO:
		case FILETYPE_PSP_ISO_NP:
			{
				info_->fileType = FILETYPE_PSP_ISO;
				SequentialHandleAllocator handles;
				// Let's assume it's an ISO.
				// TODO: This will currently read in the whole directory tree. Not really necessary for just a
				// few files.
				BlockDevice *bd = constructBlockDevice(gamePath_.c_str());
				if (!bd)
					return;  // nothing to do here..
				ISOFileSystem umd(&handles, bd, "/PSP_GAME");

				// Alright, let's fetch the PARAM.SFO.
				std::string paramSFOcontents;
				if (ReadFileToString(&umd, "/PSP_GAME/PARAM.SFO", &paramSFOcontents, 0)) {
					lock_guard lock(info_->lock);
					info_->paramSFO.ReadSFO((const u8 *)paramSFOcontents.data(), paramSFOcontents.size());
					info_->title = info_->paramSFO.GetValueString("TITLE");
					info_->id = info_->paramSFO.GetValueString("DISC_ID");
					info_->id_version = info_->paramSFO.GetValueString("DISC_ID") + "_" + info_->paramSFO.GetValueString("DISC_VERSION");
					info_->disc_total = info_->paramSFO.GetValueInt("DISC_TOTAL");
					info_->disc_number = info_->paramSFO.GetValueInt("DISC_NUMBER");

					info_->paramSFOLoaded = true;
				} else {
					// Fall back to the filename for title if ISO is broken
					info_->title = gamePath_;
				}

				ReadFileToString(&umd, "/PSP_GAME/ICON0.PNG", &info_->iconTextureData, &info_->lock);
				if (info_->wantBG) {
					ReadFileToString(&umd, "/PSP_GAME/PIC0.PNG", &info_->pic0TextureData, &info_->lock);
				}
				ReadFileToString(&umd, "/PSP_GAME/PIC1.PNG", &info_->pic1TextureData, &info_->lock);
				break;
			}
		
			case FILETYPE_NORMAL_DIRECTORY:
				info_->title = gamePath_;
				break;

			default:
			{
				std::string fn, ext;
				SplitPath(gamePath_, 0, &fn, &ext);
				info_->title = fn + "." + ext;
			}
			break;
		}
		// probably only want these when we ask for the background image...
		// should maybe flip the flag to "onlyIcon"
		if (info_->wantBG) {
			info_->gameSize = info_->GetGameSizeInBytes();
			info_->saveDataSize = info_->GetSaveDataSizeInBytes();
			info_->installDataSize = info_->GetInstallDataSizeInBytes();
		}
	}
Exemple #2
0
void MemoryCard::FlushThread()
{
	if (!SConfig::GetInstance().m_LocalCoreStartupParameter.bEnableMemcardSaving)
	{
		return;
	}

	Common::SetCurrentThreadName(
		StringFromFormat("Memcard%x-Flush", card_index).c_str());

	const auto flush_interval = std::chrono::seconds(15);

	while (true)
	{
		// If triggered, we're exiting.
		// If timed out, check if we need to flush.
		bool do_exit = m_flush_trigger.WaitFor(flush_interval);
		if (!do_exit)
		{
			bool is_dirty = m_dirty.TestAndClear();
			if (!is_dirty)
			{
				continue;
			}
		}

		// Opening the file is purposefully done each iteration to ensure the
		// file doesn't disappear out from under us after the first check.
		File::IOFile pFile(m_filename, "r+b");

		if (!pFile)
		{
			std::string dir;
			SplitPath(m_filename, &dir, nullptr, nullptr);
			if (!File::IsDirectory(dir))
			{
				File::CreateFullPath(dir);
			}
			pFile.Open(m_filename, "wb");
		}

		// Note - pFile may have changed above, after ctor
		if (!pFile)
		{
			PanicAlertT(
				"Could not write memory card file %s.\n\n"
				"Are you running Dolphin from a CD/DVD, or is the save file maybe write protected?\n\n"
				"Are you receiving this after moving the emulator directory?\nIf so, then you may "
				"need to re-specify your memory card location in the options.",
				m_filename.c_str());

			// Exit the flushing thread - further flushes will be ignored unless
			// the thread is recreated.
			return;
		}

		{
			std::unique_lock<std::mutex> l(m_flush_mutex);
			memcpy(&m_flush_buffer[0], &m_memcard_data[0], memory_card_size);
		}
		pFile.WriteBytes(&m_flush_buffer[0], memory_card_size);

		if (!do_exit)
		{
			Core::DisplayMessage(
				StringFromFormat("Wrote memory card %c contents to %s",
				card_index ? 'B' : 'A', m_filename.c_str()).c_str(),
				4000);
		}
		else
		{
			return;
		}
	}
}
bool ModelImporter::ImportAnimations()
{
    if (!animationInfo_.Size())
    {
       if (!ImportAnimation(asset_->GetPath(), "RootAnim"))
           return false;
    }

    // embedded animations
    for (unsigned i = 0; i < animationInfo_.Size(); i++)
    {
        const SharedPtr<AnimationImportInfo>& info = animationInfo_[i];
        if (!ImportAnimation(asset_->GetPath(), info->GetName(), info->GetStartTime(), info->GetEndTime()))
            return false;
    }

    // add @ animations

    FileSystem* fs = GetSubsystem<FileSystem>();
    String pathName, fileName, ext;
    SplitPath(asset_->GetPath(), pathName, fileName, ext);

    Vector<String> results;

    fs->ScanDir(results, pathName, ext, SCAN_FILES, false);

    for (unsigned i = 0; i < results.Size(); i++)
    {
        const String& result = results[i];

        if (result.Contains("@"))
        {
            Vector<String> components = GetFileName(result).Split('@');

            if (components.Size() == 2 && components[1].Length() && components[0] == fileName)
            {
                String animationName = components[1];
                AssetDatabase* db = GetSubsystem<AssetDatabase>();
                Asset* asset = db->GetAssetByPath(pathName + result);
                assert(asset);
                assert(asset->GetImporter()->GetType() == ModelImporter::GetTypeStatic());

                ModelImporter* importer = (ModelImporter*) asset->GetImporter();

                if (!importer->animationInfo_.Size())
                {
                   if (!ImportAnimation(asset->GetPath(), animationName))
                       return false;
                }
                else
                {
                    // embedded animations
                    for (unsigned i = 0; i < importer->animationInfo_.Size(); i++)
                    {
                        const SharedPtr<AnimationImportInfo>& info = importer->animationInfo_[i];
                        if (!ImportAnimation(asset->GetPath(), info->GetName(), info->GetStartTime(), info->GetEndTime()))
                            return false;
                    }
                }


            }
        }
    }



    return true;
}
Exemple #4
0
	CFilename::CFilename(const CStdStringW& path)
	{
		SplitPath(path);
	}
bool CWII_IPC_HLE_Device_fs::IOCtlV(u32 _CommandAddress)
{
	u32 ReturnValue = FS_RESULT_OK;
	SIOCtlVBuffer CommandBuffer(_CommandAddress);

	// Prepare the out buffer(s) with zeros as a safety precaution
	// to avoid returning bad values
	for (u32 i = 0; i < CommandBuffer.NumberPayloadBuffer; i++)
	{
		Memory::Memset(CommandBuffer.PayloadBuffer[i].m_Address, 0,
			CommandBuffer.PayloadBuffer[i].m_Size);
	}

	switch (CommandBuffer.Parameter)
	{
	case IOCTLV_READ_DIR:
		{
			// the wii uses this function to define the type (dir or file)
			std::string DirName(HLE_IPC_BuildFilename((const char*)Memory::GetPointer(
				CommandBuffer.InBuffer[0].m_Address), CommandBuffer.InBuffer[0].m_Size));

			INFO_LOG(WII_IPC_FILEIO, "FS: IOCTL_READ_DIR %s", DirName.c_str());

			if (!File::Exists(DirName))
			{
				WARN_LOG(WII_IPC_FILEIO, "FS: Search not found: %s", DirName.c_str());
				ReturnValue = FS_FILE_NOT_EXIST;
				break;
			}
			else if (!File::IsDirectory(DirName))
			{
				// It's not a directory, so error.
				// Games don't usually seem to care WHICH error they get, as long as it's <
				// Well the system menu CARES!
				WARN_LOG(WII_IPC_FILEIO, "\tNot a directory - return FS_RESULT_FATAL");
				ReturnValue = FS_RESULT_FATAL;
				break;
			}

			// make a file search
			CFileSearch::XStringVector Directories;
			Directories.push_back(DirName);

			CFileSearch::XStringVector Extensions;
			Extensions.push_back("*.*");

			CFileSearch FileSearch(Extensions, Directories);

			// it is one
			if ((CommandBuffer.InBuffer.size() == 1) && (CommandBuffer.PayloadBuffer.size() == 1))
			{
				size_t numFile = FileSearch.GetFileNames().size();
				INFO_LOG(WII_IPC_FILEIO, "\t%lu files found", (unsigned long)numFile);

				Memory::Write_U32((u32)numFile, CommandBuffer.PayloadBuffer[0].m_Address);
			}
			else
			{
				u32 MaxEntries = Memory::Read_U32(CommandBuffer.InBuffer[0].m_Address);

				memset(Memory::GetPointer(CommandBuffer.PayloadBuffer[0].m_Address), 0, CommandBuffer.PayloadBuffer[0].m_Size);

				size_t numFiles = 0;
				char* pFilename = (char*)Memory::GetPointer((u32)(CommandBuffer.PayloadBuffer[0].m_Address));

				for (size_t i=0; i<FileSearch.GetFileNames().size(); i++)
				{
					if (i >= MaxEntries)
						break;

					std::string name, ext;
					SplitPath(FileSearch.GetFileNames()[i], nullptr, &name, &ext);
					std::string FileName = name + ext;

					// Decode entities of invalid file system characters so that
					// games (such as HP:HBP) will be able to find what they expect.
					for (const Common::replace_t& r : replacements)
					{
						for (size_t j = 0; (j = FileName.find(r.second, j)) != FileName.npos; ++j)
							FileName.replace(j, r.second.length(), 1, r.first);
					}

					strcpy(pFilename, FileName.c_str());
					pFilename += FileName.length();
					*pFilename++ = 0x00;  // termination
					numFiles++;

					INFO_LOG(WII_IPC_FILEIO, "\tFound: %s", FileName.c_str());
				}

				Memory::Write_U32((u32)numFiles, CommandBuffer.PayloadBuffer[1].m_Address);
			}

			ReturnValue = FS_RESULT_OK;
		}
		break;

	case IOCTLV_GETUSAGE:
		{
			_dbg_assert_(WII_IPC_FILEIO, CommandBuffer.PayloadBuffer.size() == 2);
			_dbg_assert_(WII_IPC_FILEIO, CommandBuffer.PayloadBuffer[0].m_Size == 4);
			_dbg_assert_(WII_IPC_FILEIO, CommandBuffer.PayloadBuffer[1].m_Size == 4);

			// this command sucks because it asks of the number of used
			// fsBlocks and inodes
			// It should be correct, but don't count on it...
			const char *relativepath = (const char*)Memory::GetPointer(CommandBuffer.InBuffer[0].m_Address);
			std::string path(HLE_IPC_BuildFilename(relativepath, CommandBuffer.InBuffer[0].m_Size));
			u32 fsBlocks = 0;
			u32 iNodes = 0;

			INFO_LOG(WII_IPC_FILEIO, "IOCTL_GETUSAGE %s", path.c_str());
			if (File::IsDirectory(path))
			{
				// LPFaint99: After I found that setting the number of inodes to the number of children + 1 for the directory itself
				// I decided to compare with sneek which has the following 2 special cases which are
				// Copyright (C) 2009-2011  crediar http://code.google.com/p/sneek/
				if ((memcmp(relativepath, "/title/00010001", 16 ) == 0 ) ||
					(memcmp(relativepath, "/title/00010005", 16) == 0 ))
				{
					fsBlocks = 23; // size is size/0x4000
					iNodes = 42; // empty folders return a FileCount of 1
				}
				else
				{
					File::FSTEntry parentDir;
					// add one for the folder itself, allows some games to create their save files
					// R8XE52 (Jurassic: The Hunted), STEETR (Tetris Party Deluxe) now create their saves with this change
					iNodes = 1 + File::ScanDirectoryTree(path, parentDir);

					u64 totalSize = ComputeTotalFileSize(parentDir); // "Real" size, to be converted to nand blocks

					fsBlocks = (u32)(totalSize / (16 * 1024));  // one bock is 16kb
				}
				ReturnValue = FS_RESULT_OK;

				INFO_LOG(WII_IPC_FILEIO, "FS: fsBlock: %i, iNodes: %i", fsBlocks, iNodes);
			}
			else
			{
				fsBlocks = 0;
				iNodes = 0;
				ReturnValue = FS_RESULT_OK;
				WARN_LOG(WII_IPC_FILEIO, "FS: fsBlock failed, cannot find directory: %s", path.c_str());
			}

			Memory::Write_U32(fsBlocks, CommandBuffer.PayloadBuffer[0].m_Address);
			Memory::Write_U32(iNodes, CommandBuffer.PayloadBuffer[1].m_Address);
		}
		break;


	default:
		PanicAlert("CWII_IPC_HLE_Device_fs::IOCtlV: %i", CommandBuffer.Parameter);
		break;
	}

	Memory::Write_U32(ReturnValue, _CommandAddress+4);

	return true;
}
Exemple #6
0
void MenuScreen::render() {
	UIShader_Prepare();
	UIBegin(UIShader_Get());
	DrawBackground(1.0f);

	double xoff = 150 - frames_ * frames_ * 0.4f;
	if (xoff < -20)
		xoff = -20;
	if (frames_ > 200)  // seems the above goes nuts after a while...
		xoff = -20;

	int w = LARGE_BUTTON_WIDTH + 60;

	ui_draw2d.DrawTextShadow(UBUNTU48, "PPSSPP", dp_xres + xoff - w/2, 75, 0xFFFFFFFF, ALIGN_HCENTER | ALIGN_BOTTOM);
	ui_draw2d.SetFontScale(0.7f, 0.7f);
	ui_draw2d.DrawTextShadow(UBUNTU24, PPSSPP_GIT_VERSION, dp_xres + xoff, 85, 0xFFFFFFFF, ALIGN_RIGHT | ALIGN_BOTTOM);
	ui_draw2d.SetFontScale(1.0f, 1.0f);
	VLinear vlinear(dp_xres + xoff, 100, 20);

	I18NCategory *m = GetI18NCategory("MainMenu");

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Load", "Load..."), ALIGN_RIGHT)) {
#if defined(USING_QT_UI) && !defined(MEEGO_EDITION_HARMATTAN)
		QString fileName = QFileDialog::getOpenFileName(NULL, "Load ROM", g_Config.currentDirectory.c_str(), "PSP ROMs (*.iso *.cso *.pbp *.elf)");
		if (QFile::exists(fileName)) {
			QDir newPath;
			g_Config.currentDirectory = newPath.filePath(fileName).toStdString();
			g_Config.Save();
			screenManager()->switchScreen(new EmuScreen(fileName.toStdString()));
		}
#elif _WIN32
		MainWindow::BrowseAndBoot("");
#else
		FileSelectScreenOptions options;
		options.allowChooseDirectory = true;
		options.filter = "iso:cso:pbp:elf:prx:";
		options.folderIcon = I_ICON_FOLDER;
		options.iconMapping["iso"] = I_ICON_UMD;
		options.iconMapping["cso"] = I_ICON_UMD;
		options.iconMapping["pbp"] = I_ICON_EXE;
		options.iconMapping["elf"] = I_ICON_EXE;
		screenManager()->switchScreen(new FileSelectScreen(options));
#endif
		UIReset();
	}

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Settings"), ALIGN_RIGHT)) {
		screenManager()->push(new SettingsScreen(), 0);
		UIReset();
	}

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Credits"), ALIGN_RIGHT)) {
		screenManager()->switchScreen(new CreditsScreen());
		UIReset();
	}

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Exit"), ALIGN_RIGHT)) {
		// TODO: Save when setting changes, rather than when we quit
		NativeShutdown();
		// TODO: Need a more elegant way to quit
#ifdef _WIN32
		ExitProcess(0);
#else
		exit(0);
#endif
	}

	if (UIButton(GEN_ID, vlinear, w, 0, "www.ppsspp.org", ALIGN_RIGHT)) {
		LaunchBrowser("http://www.ppsspp.org/");
	}

	int recentW = 350;
	if (g_Config.recentIsos.size()) {
		ui_draw2d.DrawText(UBUNTU24, m->T("Recent"), -xoff, 80, 0xFFFFFFFF, ALIGN_BOTTOMLEFT);
	}

	int spacing = 15;

	float textureButtonWidth = 144;
	float textureButtonHeight = 80;

	if (dp_yres < 480)
		spacing = 8;
	// On small screens, we can't fit four vertically.
	if (100 + spacing * 6 + textureButtonHeight * 4 > dp_yres) {
		textureButtonHeight = (dp_yres - 100 - spacing * 6) / 4;
		textureButtonWidth = (textureButtonHeight / 80) * 144;
	}

	VGrid vgrid_recent(-xoff, 100, std::min(dp_yres-spacing*2, 480), spacing, spacing);

	for (size_t i = 0; i < g_Config.recentIsos.size(); i++) {
		std::string filename;
		std::string rec = g_Config.recentIsos[i];
		for (size_t j = 0; j < rec.size(); j++)
			if (rec[j] == '\\') rec[j] = '/';
		SplitPath(rec, nullptr, &filename, nullptr);

		UIContext *ctx = screenManager()->getUIContext();
		// This might create a texture so we must flush first.
		UIFlush();
		GameInfo *ginfo = g_gameInfoCache.GetInfo(g_Config.recentIsos[i], false);
		if (ginfo && ginfo->fileType != FILETYPE_PSP_ELF) {
			u32 color;
			if (ginfo->iconTexture == 0) {
				color = 0;
			} else {
				color = whiteAlpha(ease((time_now_d() - ginfo->timeIconWasLoaded) * 2));
			}
			if (UITextureButton(ctx, (int)GEN_ID_LOOP(i), vgrid_recent, textureButtonWidth, textureButtonHeight, ginfo->iconTexture, ALIGN_LEFT, color, I_DROP_SHADOW)) {
				UIEnd();
				screenManager()->switchScreen(new EmuScreen(g_Config.recentIsos[i]));
				return;
			}
		} else {
			if (UIButton((int)GEN_ID_LOOP(i), vgrid_recent, textureButtonWidth, textureButtonHeight, filename.c_str(), ALIGN_LEFT)) {
				UIEnd();
				screenManager()->switchScreen(new EmuScreen(g_Config.recentIsos[i]));
				return;
			}
		}
	}

#if defined(_DEBUG) & defined(_WIN32)
	// Print the current dp_xres/yres in the corner. For UI scaling testing - just
	// resize to 800x480 to get an idea of what it will look like on a Nexus S.
	ui_draw2d.SetFontScale(0.4, 0.4);
	char temptext[64];
	sprintf(temptext, "%ix%i", dp_xres, dp_yres);
	ui_draw2d.DrawTextShadow(UBUNTU24, temptext, 5, dp_yres-5, 0xFFFFFFFF, ALIGN_BOTTOMLEFT);
	ui_draw2d.SetFontScale(1.0, 1.0);
#endif

	DrawWatermark();

	UIEnd();
}
bool SConfig::AutoSetup(EBootBS2 _BootBS2)
{
	std::string set_region_dir(EUR_DIR);

	switch (_BootBS2)
	{
	case BOOT_DEFAULT:
		{
			bool bootDrive = cdio_is_cdrom(m_strFilename);
			// Check if the file exist, we may have gotten it from a --elf command line
			// that gave an incorrect file name
			if (!bootDrive && !File::Exists(m_strFilename))
			{
				PanicAlertT("The specified file \"%s\" does not exist", m_strFilename.c_str());
				return false;
			}

			std::string Extension;
			SplitPath(m_strFilename, nullptr, nullptr, &Extension);
			if (!strcasecmp(Extension.c_str(), ".gcm") ||
				!strcasecmp(Extension.c_str(), ".iso") ||
				!strcasecmp(Extension.c_str(), ".wbfs") ||
				!strcasecmp(Extension.c_str(), ".ciso") ||
				!strcasecmp(Extension.c_str(), ".gcz") ||
				bootDrive)
			{
				m_BootType = BOOT_ISO;
				std::unique_ptr<DiscIO::IVolume> pVolume(DiscIO::CreateVolumeFromFilename(m_strFilename));
				if (pVolume == nullptr)
				{
					if (bootDrive)
						PanicAlertT("Could not read \"%s\".  "
								"There is no disc in the drive, or it is not a GC/Wii backup.  "
								"Please note that original GameCube and Wii discs cannot be read "
								"by most PC DVD drives.", m_strFilename.c_str());
					else
						PanicAlertT("\"%s\" is an invalid GCM/ISO file, or is not a GC/Wii ISO.",
								m_strFilename.c_str());
					return false;
				}
				m_strName = pVolume->GetInternalName();
				m_strUniqueID = pVolume->GetUniqueID();
				m_revision = pVolume->GetRevision();

				// Check if we have a Wii disc
				bWii = pVolume.get()->GetVolumeType() == DiscIO::IVolume::WII_DISC;

				const char* retrieved_region_dir = GetRegionOfCountry(pVolume->GetCountry());
				if (!retrieved_region_dir)
				{
					if (!PanicYesNoT("Your GCM/ISO file seems to be invalid (invalid country)."
						"\nContinue with PAL region?"))
						return false;
					retrieved_region_dir = EUR_DIR;
				}

				set_region_dir = retrieved_region_dir;
				bNTSC = set_region_dir == USA_DIR || set_region_dir == JAP_DIR;
			}
			else if (!strcasecmp(Extension.c_str(), ".elf"))
			{
				bWii = CBoot::IsElfWii(m_strFilename);
				// TODO: Right now GC homebrew boots in NTSC and Wii homebrew in PAL.
				// This is intentional so that Wii homebrew can boot in both 50Hz and 60Hz, without forcing all GC homebrew to 50Hz.
				// In the future, it probably makes sense to add a Region setting for homebrew somewhere in the emulator config.
				bNTSC = bWii ? false : true;
				set_region_dir = bNTSC ? USA_DIR : EUR_DIR;
				m_BootType = BOOT_ELF;
			}
			else if (!strcasecmp(Extension.c_str(), ".dol"))
			{
				CDolLoader dolfile(m_strFilename);
				bWii = dolfile.IsWii();
				// TODO: See the ELF code above.
				bNTSC = bWii ? false : true;
				set_region_dir = bNTSC ? USA_DIR : EUR_DIR;
				m_BootType = BOOT_DOL;
			}
			else if (!strcasecmp(Extension.c_str(), ".dff"))
			{
				bWii = true;
				set_region_dir = USA_DIR;
				bNTSC = true;
				m_BootType = BOOT_DFF;

				std::unique_ptr<FifoDataFile> ddfFile(FifoDataFile::Load(m_strFilename, true));

				if (ddfFile)
				{
					bWii = ddfFile->GetIsWii();
				}
			}
			else if (DiscIO::CNANDContentManager::Access().GetNANDLoader(m_strFilename).IsValid())
			{
				std::unique_ptr<DiscIO::IVolume> pVolume(DiscIO::CreateVolumeFromFilename(m_strFilename));
				const DiscIO::INANDContentLoader& ContentLoader = DiscIO::CNANDContentManager::Access().GetNANDLoader(m_strFilename);

				if (ContentLoader.GetContentByIndex(ContentLoader.GetBootIndex()) == nullptr)
				{
					//WAD is valid yet cannot be booted. Install instead.
					u64 installed = DiscIO::CNANDContentManager::Access().Install_WiiWAD(m_strFilename);
					if (installed)
						SuccessAlertT("The WAD has been installed successfully");
					return false; //do not boot
				}

				const char* retrieved_region_dir = GetRegionOfCountry(ContentLoader.GetCountry());
				set_region_dir = retrieved_region_dir ? retrieved_region_dir : EUR_DIR;
				bNTSC = set_region_dir == USA_DIR || set_region_dir == JAP_DIR;

				bWii = true;
				m_BootType = BOOT_WII_NAND;

				if (pVolume)
				{
					m_strName = pVolume->GetInternalName();
					m_strUniqueID = pVolume->GetUniqueID();
				}
				else
				{
					// null pVolume means that we are loading from nand folder (Most Likely Wii Menu)
					// if this is the second boot we would be using the Name and id of the last title
					m_strName.clear();
					m_strUniqueID.clear();
				}

				// Use the TitleIDhex for name and/or unique ID if launching from nand folder
				// or if it is not ascii characters (specifically sysmenu could potentially apply to other things)
				std::string titleidstr = StringFromFormat("%016" PRIx64, ContentLoader.GetTitleID());

				if (m_strName.empty())
				{
					m_strName = titleidstr;
				}
				if (m_strUniqueID.empty())
				{
					m_strUniqueID = titleidstr;
				}
			}
			else
			{
				PanicAlertT("Could not recognize ISO file %s", m_strFilename.c_str());
				return false;
			}
		}
		break;

	case BOOT_BS2_USA:
		set_region_dir = USA_DIR;
		m_strFilename.clear();
		bNTSC = true;
		break;

	case BOOT_BS2_JAP:
		set_region_dir = JAP_DIR;
		m_strFilename.clear();
		bNTSC = true;
		break;

	case BOOT_BS2_EUR:
		set_region_dir = EUR_DIR;
		m_strFilename.clear();
		bNTSC = false;
		break;
	}

	// Setup paths
	CheckMemcardPath(SConfig::GetInstance().m_strMemoryCardA, set_region_dir, true);
	CheckMemcardPath(SConfig::GetInstance().m_strMemoryCardB, set_region_dir, false);
	m_strSRAM = File::GetUserPath(F_GCSRAM_IDX);
	if (!bWii)
	{
		if (!bHLE_BS2)
		{
			m_strBootROM = File::GetUserPath(D_GCUSER_IDX) + DIR_SEP + set_region_dir + DIR_SEP GC_IPL;
			if (!File::Exists(m_strBootROM))
				m_strBootROM = File::GetSysDirectory() + GC_SYS_DIR + DIR_SEP + set_region_dir + DIR_SEP GC_IPL;

			if (!File::Exists(m_strBootROM))
			{
				WARN_LOG(BOOT, "Bootrom file %s not found - using HLE.", m_strBootROM.c_str());
				bHLE_BS2 = true;
			}
		}
	}
	else if (bWii && !bHLE_BS2)
	{
		WARN_LOG(BOOT, "GC bootrom file will not be loaded for Wii mode.");
		bHLE_BS2 = true;
	}

	return true;
}
Exemple #8
0
void CGameListCtrl::ScanForISOs()
{
    ClearIsoFiles();

    CFileSearch::XStringVector Directories(SConfig::GetInstance().m_ISOFolder);

    if (SConfig::GetInstance().m_RecursiveISOFolder)
    {
        for (u32 i = 0; i < Directories.size(); i++)
        {
            File::FSTEntry FST_Temp;
            File::ScanDirectoryTree(Directories[i], FST_Temp);
            for (auto& Entry : FST_Temp.children)
            {
                if (Entry.isDirectory)
                {
                    bool duplicate = false;
                    for (auto& Directory : Directories)
                    {
                        if (Directory == Entry.physicalName)
                        {
                            duplicate = true;
                            break;
                        }
                    }
                    if (!duplicate)
                        Directories.push_back(Entry.physicalName);
                }
            }
        }
    }

    CFileSearch::XStringVector Extensions;

    if (SConfig::GetInstance().m_ListGC)
        Extensions.push_back("*.gcm");
    if (SConfig::GetInstance().m_ListWii || SConfig::GetInstance().m_ListGC)
    {
        Extensions.push_back("*.iso");
        Extensions.push_back("*.ciso");
        Extensions.push_back("*.gcz");
        Extensions.push_back("*.wbfs");
    }
    if (SConfig::GetInstance().m_ListWad)
        Extensions.push_back("*.wad");

    CFileSearch FileSearch(Extensions, Directories);
    const CFileSearch::XStringVector& rFilenames = FileSearch.GetFileNames();

    if (rFilenames.size() > 0)
    {
        wxProgressDialog dialog(
            _("Scanning for ISOs"),
            _("Scanning..."),
            (int)rFilenames.size() - 1,
            this,
            wxPD_APP_MODAL |
            wxPD_AUTO_HIDE |
            wxPD_CAN_ABORT |
            wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME |
            wxPD_SMOOTH // - makes updates as small as possible (down to 1px)
        );

        for (u32 i = 0; i < rFilenames.size(); i++)
        {
            std::string FileName;
            SplitPath(rFilenames[i], nullptr, &FileName, nullptr);

            // Update with the progress (i) and the message
            dialog.Update(i, wxString::Format(_("Scanning %s"),
                                              StrToWxStr(FileName)));
            if (dialog.WasCancelled())
                break;

            auto iso_file = std::make_unique<GameListItem>(rFilenames[i]);

            if (iso_file->IsValid())
            {
                bool list = true;

                switch(iso_file->GetPlatform())
                {
                case GameListItem::WII_DISC:
                    if (!SConfig::GetInstance().m_ListWii)
                        list = false;
                    break;
                case GameListItem::WII_WAD:
                    if (!SConfig::GetInstance().m_ListWad)
                        list = false;
                    break;
                default:
                    if (!SConfig::GetInstance().m_ListGC)
                        list = false;
                    break;
                }

                switch(iso_file->GetCountry())
                {
                case DiscIO::IVolume::COUNTRY_TAIWAN:
                    if (!SConfig::GetInstance().m_ListTaiwan)
                        list = false;
                    break;
                case DiscIO::IVolume::COUNTRY_KOREA:
                    if (!SConfig::GetInstance().m_ListKorea)
                        list = false;
                    break;
                case DiscIO::IVolume::COUNTRY_JAPAN:
                    if (!SConfig::GetInstance().m_ListJap)
                        list = false;
                    break;
                case DiscIO::IVolume::COUNTRY_USA:
                    if (!SConfig::GetInstance().m_ListUsa)
                        list = false;
                    break;
                case DiscIO::IVolume::COUNTRY_FRANCE:
                    if (!SConfig::GetInstance().m_ListFrance)
                        list = false;
                    break;
                case DiscIO::IVolume::COUNTRY_ITALY:
                    if (!SConfig::GetInstance().m_ListItaly)
                        list = false;
                    break;
                default:
                    if (!SConfig::GetInstance().m_ListPal)
                        list = false;
                    break;
                }

                if (list)
                    m_ISOFiles.push_back(iso_file.release());
            }
        }
    }

    if (SConfig::GetInstance().m_ListDrives)
    {
        const std::vector<std::string> drives = cdio_get_devices();

        for (const auto& drive : drives)
        {
            auto gli = std::make_unique<GameListItem>(drive);

            if (gli->IsValid())
                m_ISOFiles.push_back(gli.release());
        }
    }

    std::sort(m_ISOFiles.begin(), m_ISOFiles.end());
}
Exemple #9
0
//*****************************************************************************
// Open the base file on top of: (a) file, (b) memory buffer, or (c) stream.
// If create flag is specified, then this will create a new file with the
// name supplied.  No data is read from an opened file.  You must call
// MapFileToMem before doing direct pointer access to the contents.
//*****************************************************************************
HRESULT StgIO::Open(                    // Return code.
    LPCWSTR     szName,                 // Name of the storage.
    int        fFlags,                 // How to open the file.
    const void  *pbBuff,                // Optional buffer for memory.
    ULONG       cbBuff,                 // Size of buffer.
    IStream     *pIStream,              // Stream for input.
    LPSECURITY_ATTRIBUTES pAttributes)  // Security token.
{
    HRESULT hr;
    
    // If we were given the storage memory to begin with, then use it.
    if (pbBuff && cbBuff)
    {
        _ASSERTE((fFlags & DBPROP_TMODEF_WRITE) == 0);

        // Save the memory address and size only.  No handles.
        m_pData = (void *) pbBuff;
        m_cbData = cbBuff;

#ifndef FEATURE_METADATA_STANDALONE_WINRT_RO
        // All access to data will be by memory provided.
        if ((fFlags & DBPROP_TMODEF_SHAREDMEM) == DBPROP_TMODEF_SHAREDMEM)
        {
            // We're taking ownership of this memory
            m_pBaseData = m_pData;
            m_iType = STGIO_SHAREDMEM;
        }
        else
#endif //!FEATURE_METADATA_STANDALONE_WINRT_RO
        {
            m_iType = STGIO_MEM;
        }
        goto ErrExit;
    }
    // Check for data backed by a stream pointer.
    else if (pIStream)
    {
        // If this is for the non-create case, get the size of existing data.
        if ((fFlags & DBPROP_TMODEF_CREATE) == 0)
        {
            LARGE_INTEGER   iMove = { { 0, 0 } };
            ULARGE_INTEGER  iSize;

            // Need the size of the data so we can map it into memory.
            if (FAILED(hr = pIStream->Seek(iMove, STREAM_SEEK_END, &iSize)))
                return (hr);
            m_cbData = iSize.u.LowPart;
        }
        // Else there is nothing.
        else
            m_cbData = 0;

        // Save an addref'd copy of the stream.
        m_pIStream = pIStream;
        m_pIStream->AddRef();

        // All access to data will be by memory provided.
        m_iType = STGIO_STREAM;
        goto ErrExit;
    }

    // If not on memory, we need a file to do a create/open.
    if (!szName || !*szName)
    {
        return (PostError(E_INVALIDARG));
    }
    // Check for create of a new file.
    else if (fFlags & DBPROP_TMODEF_CREATE)
    {
        //<REVISIT_TODO>@future: This could chose to open the file in write through
        // mode, which would provide better Duribility (from ACID props),
        // but would be much slower.</REVISIT_TODO>

        // Create the new file, overwriting only if caller allows it.
        if ((m_hFile = WszCreateFile(szName, GENERIC_READ | GENERIC_WRITE, 0, 0, 
                (fFlags & DBPROP_TMODEF_FAILIFTHERE) ? CREATE_NEW : CREATE_ALWAYS, 
                0, 0)) == INVALID_HANDLE_VALUE)
        {
            return (MapFileError(GetLastError()));
        }

        // Data will come from the file.
        m_iType = STGIO_HFILE;
    }
    // For open in read mode, need to open the file on disk.  If opening a shared
    // memory view, it has to be opened already, so no file open.
    else if ((fFlags & DBPROP_TMODEF_WRITE) == 0)
    {
        // We have not opened the file nor loaded it as module
        _ASSERTE(m_hFile == INVALID_HANDLE_VALUE);
        _ASSERTE(m_hModule == NULL);

        // Open the file for read.  Sharing is determined by caller, it can
        // allow other readers or be exclusive.
        DWORD dwFileSharingFlags = FILE_SHARE_DELETE;
        if (!(fFlags & DBPROP_TMODEF_EXCLUSIVE))
        {
            dwFileSharingFlags |= FILE_SHARE_READ;
            
#if !defined(DACCESS_COMPILE) && !defined(FEATURE_PAL) 
            // PEDecoder is not defined in DAC
            
            // We prefer to use LoadLibrary if we can because it will share already loaded images (used for execution) 
            // which saves virtual memory. We only do this if our caller has indicated that this PE file is trusted 
            // and thus it is OK to do LoadLibrary (note that we still only load it as a resource, which mitigates 
            // most of the security risk anyway).
            if ((fFlags & DBPROP_TMODEF_TRYLOADLIBRARY) != 0)
            {
                m_hModule = WszLoadLibraryEx(szName, NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE);
                if (m_hModule != NULL)
                {
                    m_iType = STGIO_HMODULE;
                    
                    m_mtMappedType = MTYPE_IMAGE;
                    
                    // LoadLibraryEx returns 2 lowest bits indicating how the module was loaded
                    m_pBaseData = m_pData = (void *)(((INT_PTR)m_hModule) & ~(INT_PTR)0x3);
                    
                    PEDecoder peDecoder;
                    if (SUCCEEDED(peDecoder.Init(
                                m_pBaseData, 
                                false)) &&  // relocated
                        peDecoder.CheckNTHeaders())
                    {
                        m_cbData = peDecoder.GetNTHeaders32()->OptionalHeader.SizeOfImage;
                    }
                    else
                    {
                        // PEDecoder failed on loaded library, let's backout all our changes to this object 
                        // and fall back to file mapping
                        m_iType = STGIO_NODATA;
                        m_mtMappedType = MTYPE_NOMAPPING;
                        m_pBaseData = m_pData = NULL;
                        
                        FreeLibrary(m_hModule);
                        m_hModule = NULL;
                    }
                }
            }
#endif //!DACCESS_COMPILE && !FEATURE_PAL
        }

        if (m_hModule == NULL)
        {   // We didn't get the loaded module (we either didn't want to or it failed)
            HandleHolder hFile(WszCreateFile(szName, 
                                             GENERIC_READ, 
                                             dwFileSharingFlags,
                                             0, 
                                             OPEN_EXISTING, 
                                             0, 
                                             0));

            if (hFile == INVALID_HANDLE_VALUE)
                return (MapFileError(GetLastError()));

            // Get size of file.
            m_cbData = ::SetFilePointer(hFile, 0, 0, FILE_END);

            // Can't read anything from an empty file.
            if (m_cbData == 0)
                return (PostError(CLDB_E_NO_DATA));

            // Data will come from the file.
            m_hFile = hFile.Extract();
            
            m_iType = STGIO_HFILE;
        }
    }

ErrExit:

    // If we will ever write, then we need the buffer cache.
    if (fFlags & DBPROP_TMODEF_WRITE)
    {
        // Allocate a cache buffer for writing.
        if ((m_rgBuff = (BYTE *) AllocateMemory(m_iCacheSize)) == NULL)
        {
            Close();
            return PostError(OutOfMemory());
        }
        m_cbBuff = 0;
    }
    
    // Save flags for later.
    m_fFlags = fFlags;
    if ((szName != NULL) && (*szName != 0))
    {
        WCHAR rcExt[_MAX_PATH];
        SplitPath(szName, NULL, 0, NULL, 0, NULL, 0, rcExt, _MAX_PATH);
        if (SString::_wcsicmp(rcExt, W(".obj")) == 0)
        {
            m_FileType = FILETYPE_NTOBJ;
        }
        else if (SString::_wcsicmp(rcExt, W(".tlb")) == 0)
        {
            m_FileType = FILETYPE_TLB;
        }
    }

    // For auto map case, map the view of the file as part of open.
    if (m_bAutoMap && 
        (m_iType == STGIO_HFILE || m_iType == STGIO_STREAM) &&
        !(fFlags & DBPROP_TMODEF_CREATE))
    {
        void * ptr;
        ULONG  cb;
        
        if (FAILED(hr = MapFileToMem(ptr, &cb, pAttributes)))
        {
            Close();
            return hr;
        }
    }
    return S_OK;
} // StgIO::Open
Exemple #10
0
void HiresTexture::Update()
{
  if (s_prefetcher.joinable())
  {
    s_textureCacheAbortLoading.Set();
    s_prefetcher.join();
  }

  if (!g_ActiveConfig.bHiresTextures)
  {
    s_textureMap.clear();
    s_textureCache.clear();
    return;
  }

  if (!g_ActiveConfig.bCacheHiresTextures)
  {
    s_textureCache.clear();
  }

  const std::string& game_id = SConfig::GetInstance().m_strUniqueID;
  const std::string texture_directory = GetTextureDirectory(game_id);
  std::vector<std::string> extensions{
      ".png", ".bmp", ".tga", ".dds",
      ".jpg"  // Why not? Could be useful for large photo-like textures
  };

  std::vector<std::string> filenames =
      DoFileSearch(extensions, {texture_directory}, /*recursive*/ true);

  const std::string code = game_id + "_";

  for (auto& rFilename : filenames)
  {
    std::string FileName;
    SplitPath(rFilename, nullptr, &FileName, nullptr);

    if (FileName.substr(0, code.length()) == code)
    {
      s_textureMap[FileName] = rFilename;
      s_check_native_format = true;
    }

    if (FileName.substr(0, s_format_prefix.length()) == s_format_prefix)
    {
      s_textureMap[FileName] = rFilename;
      s_check_new_format = true;
    }
  }

  if (g_ActiveConfig.bCacheHiresTextures)
  {
    // remove cached but deleted textures
    auto iter = s_textureCache.begin();
    while (iter != s_textureCache.end())
    {
      if (s_textureMap.find(iter->first) == s_textureMap.end())
      {
        iter = s_textureCache.erase(iter);
      }
      else
      {
        iter++;
      }
    }

    s_textureCacheAbortLoading.Clear();
    s_prefetcher = std::thread(Prefetch);
  }
}
void Init(const char *gameCode)
{
	textureMap.clear();
	texturecount = 0;
	CFileSearch::XStringVector Directories;
	//Directories.push_back(File::GetUserPath(D_HIRESTEXTURES_IDX));
	char szDir[MAX_PATH];
	sprintf(szDir, "%s%s", File::GetUserPath(D_HIRESTEXTURES_IDX).c_str(), gameCode);
	Directories.push_back(std::string(szDir));
	

	for (u32 i = 0; i < Directories.size(); i++)
	{
		File::FSTEntry FST_Temp;
		File::ScanDirectoryTree(Directories[i], FST_Temp);
		for (u32 j = 0; j < FST_Temp.children.size(); j++)
		{
			if (FST_Temp.children.at(j).isDirectory)
			{
				bool duplicate = false;
				for (u32 k = 0; k < Directories.size(); k++)
				{
					if (strcmp(Directories[k].c_str(), FST_Temp.children.at(j).physicalName.c_str()) == 0)
					{
						duplicate = true;
						break;
					}
				}
				if (!duplicate)
					Directories.push_back(FST_Temp.children.at(j).physicalName.c_str());
			}
		}
	}

	CFileSearch::XStringVector Extensions;
	Extensions.push_back("*.png");
	Extensions.push_back("*.PNG");
	Extensions.push_back("*.bmp");
	Extensions.push_back("*.BMP");
	Extensions.push_back("*.tga");
	Extensions.push_back("*.TGA");
	Extensions.push_back("*.dds");
	Extensions.push_back("*.DDS");
	Extensions.push_back("*.jpg"); // Why not? Could be useful for large photo-like textures
	Extensions.push_back("*.JPG");
	CFileSearch FileSearch(Extensions, Directories);
	const CFileSearch::XStringVector& rFilenames = FileSearch.GetFileNames();
	std::string code(gameCode);

	if (rFilenames.size() > 0)
	{
		for (u32 i = 0; i < rFilenames.size(); i++)
		{
			std::string FileName;
			std::string Extension;			
			SplitPath(rFilenames[i], NULL, &FileName, &Extension);
			std::pair<std::string, std::string> Pair(rFilenames[i], Extension);
			std::vector<std::string> nameparts;
			std::istringstream issfilename(FileName);
			std::string nameitem;
			while (std::getline(issfilename, nameitem, '_')) {
				nameparts.push_back(nameitem);
			}
			if (nameparts.size() >= 3)
			{
				u32 hash = 0;
				u32 format = 0;
				u32 mip = 0;
				sscanf(nameparts[1].c_str(), "%x", &hash);
				sscanf(nameparts[2].c_str(), "%i", &format);
				if (nameparts.size() > 3 && nameparts[3].size() > 3)
				{
					sscanf(nameparts[3].substr(3, std::string::npos).c_str(), "%i", &mip);
				}
				u64 key = ((u64)hash) | (((u64)format) << 32) | (((u64)mip) << 48);
				if (nameparts[0].compare(code) == 0 && textureMap.find(key) == textureMap.end())
				{
					texturecount++;
					textureMap.insert(std::map<u64, std::pair<std::string, std::string>>::value_type(key, Pair));
				}
			}
			
		}
	}
}
void BuildWindows::BuildAtomicNET()
{
    // AtomicNET

    FileSystem* fileSystem = GetSubsystem<FileSystem>();
    ToolEnvironment* tenv = GetSubsystem<ToolEnvironment>();
    ToolSystem* tsystem = GetSubsystem<ToolSystem>();
    Project* project = tsystem->GetProject();
    String projectResources = project->GetResourcePath();

    String assembliesPath = projectResources + "Assemblies/";

    // if no assemblies path, no need to install AtomicNET
    if (!fileSystem->DirExists(assembliesPath))
        return;

    Vector<String> results;
    fileSystem->ScanDir(results, assembliesPath, "*.dll", SCAN_FILES, true);

    // if no assembiles in Assemblies path, no need to install AtomicNET
    if (!results.Size())
        return;

    BuildLog("Building AtomicNET");

    fileSystem->CreateDir(buildPath_ + "/AtomicPlayer_Resources/AtomicNET");
    fileSystem->CreateDir(buildPath_ + "/AtomicPlayer_Resources/AtomicNET/Atomic");
    fileSystem->CreateDir(buildPath_ + "/AtomicPlayer_Resources/AtomicNET/Atomic/Assemblies");

    fileSystem->CopyDir(tenv->GetNETCoreCLRAbsPath(), buildPath_ + "/AtomicPlayer_Resources/AtomicNET/CoreCLR");
    fileSystem->CopyDir(tenv->GetNETTPAPaths(), buildPath_ + "/AtomicPlayer_Resources/AtomicNET/Atomic/TPA");

    // Atomic Assemblies

    const String& assemblyLoadPaths = tenv->GetNETAssemblyLoadPaths();
    Vector<String> paths = assemblyLoadPaths.Split(';');

    for (unsigned i = 0; i < paths.Size(); i++)
    {
        Vector<String> loadResults;
        fileSystem->ScanDir(loadResults, paths[i], "*.dll", SCAN_FILES, true);

        for (unsigned j = 0; j < loadResults.Size(); j++)
        {
            String pathName, fileName, ext;
            SplitPath(loadResults[j], pathName, fileName, ext);

            if (fileName != "AtomicNETEngine")
                continue;

            fileSystem->Copy(paths[i] + "/" + loadResults[j], ToString("%s/AtomicPlayer_Resources/AtomicNET/Atomic/Assemblies/%s.dll", buildPath_.CString(), fileName.CString()));
        }

    }

    // Project assemblied
    for (unsigned i = 0; i < results.Size(); i++)
    {
        String pathName, fileName, ext;
        SplitPath(results[i], pathName, fileName, ext);
        fileSystem->Copy(assembliesPath + results[i], ToString("%s/AtomicPlayer_Resources/AtomicNET/Atomic/Assemblies/%s.dll", buildPath_.CString(), fileName.CString()));
    }



}
void GameCubeConfigPane::ChooseSlotPath(bool is_slot_a, TEXIDevices device_type)
{
	bool memcard = (device_type == EXIDEVICE_MEMORYCARD);
	std::string path;
	std::string cardname;
	std::string ext;
	std::string pathA = SConfig::GetInstance().m_strMemoryCardA;
	std::string pathB = SConfig::GetInstance().m_strMemoryCardB;
	if (!memcard)
	{
		pathA = SConfig::GetInstance().m_strGbaCartA;
		pathB = SConfig::GetInstance().m_strGbaCartB;
	}
	SplitPath(is_slot_a ? pathA : pathB, &path, &cardname, &ext);
	std::string filename = WxStrToStr(wxFileSelector(
		_("Choose a file to open"),
		StrToWxStr(path),
		StrToWxStr(cardname),
		StrToWxStr(ext),
		memcard ? _("GameCube Memory Cards (*.raw,*.gcp)") + "|*.raw;*.gcp" : _("Game Boy Advance Carts (*.gba)") + "|*.gba"));

	if (!filename.empty())
	{
		if (File::Exists(filename))
		{
			if (memcard)
			{
				GCMemcard memorycard(filename);
				if (!memorycard.IsValid())
				{
					WxUtils::ShowErrorDialog(wxString::Format(_("Cannot use that file as a memory card.\n%s\n" \
						"is not a valid GameCube memory card file"), filename.c_str()));
					return;
				}
			}
		}

		wxFileName newFilename(filename);
		newFilename.MakeAbsolute();
		filename = newFilename.GetFullPath();

#ifdef _WIN32
		// If the Memory Card file is within the Exe dir, we can assume that the user wants it to be stored relative
		// to the executable, so it stays set correctly when the probably portable Exe dir is moved.
		// TODO: Replace this with a cleaner, non-wx solution once std::filesystem is standard
		std::string exeDir = File::GetExeDirectory() + '\\';
		if (wxString(filename).Lower().StartsWith(wxString(exeDir).Lower()))
			filename.erase(0, exeDir.size());

		std::replace(filename.begin(), filename.end(), '\\', '/');
#endif

		// also check that the path isn't used for the other memcard...
		wxFileName otherFilename(is_slot_a ? pathB : pathA);
		otherFilename.MakeAbsolute();
		if (newFilename.GetFullPath().compare(otherFilename.GetFullPath()) != 0)
		{
			if (memcard)
			{
				if (is_slot_a)
					SConfig::GetInstance().m_strMemoryCardA = filename;
				else
					SConfig::GetInstance().m_strMemoryCardB = filename;
			}
			else
			{
				if (is_slot_a)
					SConfig::GetInstance().m_strGbaCartA = filename;
				else
					SConfig::GetInstance().m_strGbaCartB = filename;
			}

			if (Core::IsRunning())
			{
				// Change memcard to the new file
				ExpansionInterface::ChangeDevice(
					is_slot_a ? 0 : 1, // SlotA: channel 0, SlotB channel 1
					device_type,
					0); // SP1 is device 2, slots are device 0
			}
		}
		else
		{
			WxUtils::ShowErrorDialog(_("Are you trying to use the same file in both slots?"));
		}
	}
}
Exemple #14
0
void CGameListCtrl::CompressSelection(bool _compress)
{
    wxString dirHome;
    wxGetHomeDir(&dirHome);

    wxDirDialog browseDialog(this, _("Browse for output directory"), dirHome,
                             wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
    if (browseDialog.ShowModal() != wxID_OK)
        return;

    bool all_good = true;

    {
        wxProgressDialog progressDialog(
            _compress ? _("Compressing ISO") : _("Decompressing ISO"),
            _("Working..."),
            1000,
            this,
            wxPD_APP_MODAL |
            wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME |
            wxPD_SMOOTH
        );

        m_currentItem = 0;
        m_numberItem = GetSelectedItemCount();
        for (u32 i=0; i < m_numberItem; i++)
        {
            const GameListItem *iso = GetSelectedISO();

            if (!iso->IsCompressed() && _compress)
            {
                std::string FileName, FileExt;
                SplitPath(iso->GetFileName(), nullptr, &FileName, &FileExt);
                m_currentFilename = FileName;
                FileName.append(".gcz");

                std::string OutputFileName;
                BuildCompleteFilename(OutputFileName,
                                      WxStrToStr(browseDialog.GetPath()),
                                      FileName);

                if (wxFileExists(StrToWxStr(OutputFileName)) &&
                        wxMessageBox(
                            wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"),
                                             StrToWxStr(OutputFileName)),
                            _("Confirm File Overwrite"),
                            wxYES_NO) == wxNO)
                    continue;

                all_good &= DiscIO::CompressFileToBlob(iso->GetFileName(),
                                                       OutputFileName,
                                                       (iso->GetPlatform() == GameListItem::WII_DISC) ? 1 : 0,
                                                       16384, &MultiCompressCB, &progressDialog);
            }
            else if (iso->IsCompressed() && !_compress)
            {
                std::string FileName, FileExt;
                SplitPath(iso->GetFileName(), nullptr, &FileName, &FileExt);
                m_currentFilename = FileName;
                if (iso->GetPlatform() == GameListItem::WII_DISC)
                    FileName.append(".iso");
                else
                    FileName.append(".gcm");

                std::string OutputFileName;
                BuildCompleteFilename(OutputFileName,
                                      WxStrToStr(browseDialog.GetPath()),
                                      FileName);

                if (wxFileExists(StrToWxStr(OutputFileName)) &&
                        wxMessageBox(
                            wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"),
                                             StrToWxStr(OutputFileName)),
                            _("Confirm File Overwrite"),
                            wxYES_NO) == wxNO)
                    continue;

                all_good &= DiscIO::DecompressBlobToFile(iso->GetFileName().c_str(),
                            OutputFileName.c_str(), &MultiCompressCB, &progressDialog);
            }
            m_currentItem++;
        }
    }

    if (!all_good)
        WxUtils::ShowErrorDialog(_("Dolphin was unable to complete the requested action."));

    Update();
}
Exemple #15
0
void MemoryCard::FlushThread()
{
	if (!Core::g_CoreStartupParameter.bEnableMemcardSaving)
	{
		return;
	}

	Common::SetCurrentThreadName(
		StringFromFormat("Memcard%x-Flush", card_index).c_str());

	const auto flush_interval = std::chrono::seconds(15);
	auto last_flush = std::chrono::steady_clock::now();
	bool dirty = false;

	for (;;)
	{
		bool triggered = m_flush_trigger.WaitFor(flush_interval);
		bool do_exit = m_is_exiting.IsSet();
		if (triggered)
		{
			dirty = true;
		}
		// Delay the flush if we're not exiting or if the event timed out and
		// the state isn't dirty.
		if (!do_exit)
		{
			auto now = std::chrono::steady_clock::now();
			if (now - last_flush < flush_interval || !dirty)
			{
				continue;
			}
			last_flush = now;
		}

		// Opening the file is purposefully done each iteration to ensure the
		// file doesn't disappear out from under us after the first check.
		File::IOFile pFile(m_filename, "r+b");

		if (!pFile)
		{
			std::string dir;
			SplitPath(m_filename, &dir, nullptr, nullptr);
			if (!File::IsDirectory(dir))
			{
				File::CreateFullPath(dir);
			}
			pFile.Open(m_filename, "wb");
		}

		// Note - pFile may have changed above, after ctor
		if (!pFile)
		{
			PanicAlertT(
				"Could not write memory card file %s.\n\n"
				"Are you running Dolphin from a CD/DVD, or is the save file maybe write protected?\n\n"
				"Are you receiving this after moving the emulator directory?\nIf so, then you may "
				"need to re-specify your memory card location in the options.",
				m_filename.c_str());

			// Exit the flushing thread - further flushes will be ignored unless
			// the thread is recreated.
			return;
		}

		{
			std::unique_lock<std::mutex> l(m_flush_mutex);
			pFile.WriteBytes(&m_flush_buffer[0], memory_card_size);
		}

		dirty = false;

		if (!do_exit)
		{
			Core::DisplayMessage(
				StringFromFormat("Wrote memory card %c contents to %s",
				card_index ? 'B' : 'A', m_filename.c_str()).c_str(),
				4000);
		}
		else
		{
			return;
		}
	}
}
Exemple #16
0
void CGameListCtrl::OnCompressGCM(wxCommandEvent& WXUNUSED (event))
{
    const GameListItem *iso = GetSelectedISO();
    if (!iso)
        return;

    wxString path;

    std::string FileName, FilePath, FileExtension;
    SplitPath(iso->GetFileName(), &FilePath, &FileName, &FileExtension);

    do
    {
        if (iso->IsCompressed())
        {
            wxString FileType;
            if (iso->GetPlatform() == GameListItem::WII_DISC)
                FileType = _("All Wii ISO files (iso)") + "|*.iso";
            else
                FileType = _("All GameCube GCM files (gcm)") + "|*.gcm";

            path = wxFileSelector(
                       _("Save decompressed GCM/ISO"),
                       StrToWxStr(FilePath),
                       StrToWxStr(FileName) + FileType.After('*'),
                       wxEmptyString,
                       FileType + "|" + wxGetTranslation(wxALL_FILES),
                       wxFD_SAVE,
                       this);
        }
        else
        {
            path = wxFileSelector(
                       _("Save compressed GCM/ISO"),
                       StrToWxStr(FilePath),
                       StrToWxStr(FileName) + ".gcz",
                       wxEmptyString,
                       _("All compressed GC/Wii ISO files (gcz)") +
                       wxString::Format("|*.gcz|%s", wxGetTranslation(wxALL_FILES)),
                       wxFD_SAVE,
                       this);
        }
        if (!path)
            return;
    } while (wxFileExists(path) &&
             wxMessageBox(
                 wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"), path.c_str()),
                 _("Confirm File Overwrite"),
                 wxYES_NO) == wxNO);

    bool all_good = false;

    {
        wxProgressDialog dialog(
            iso->IsCompressed() ? _("Decompressing ISO") : _("Compressing ISO"),
            _("Working..."),
            1000,
            this,
            wxPD_APP_MODAL |
            wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME |
            wxPD_SMOOTH
        );


        if (iso->IsCompressed())
            all_good = DiscIO::DecompressBlobToFile(iso->GetFileName(),
                                                    WxStrToStr(path), &CompressCB, &dialog);
        else
            all_good = DiscIO::CompressFileToBlob(iso->GetFileName(),
                                                  WxStrToStr(path),
                                                  (iso->GetPlatform() == GameListItem::WII_DISC) ? 1 : 0,
                                                  16384, &CompressCB, &dialog);
    }

    if (!all_good)
        WxUtils::ShowErrorDialog(_("Dolphin was unable to complete the requested action."));

    Update();
}
void CMemcardManager::CopyDeleteClick(wxCommandEvent& event)
{
	int index_A = m_MemcardList[SLOT_A]->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
	int index_B = m_MemcardList[SLOT_B]->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
	int slot = SLOT_B;
	int slot2 = SLOT_A;
	std::string fileName2("");

	if (index_A != wxNOT_FOUND && page[SLOT_A]) index_A += itemsPerPage * page[SLOT_A];
	if (index_B != wxNOT_FOUND && page[SLOT_B]) index_B += itemsPerPage * page[SLOT_B];

	int index = index_B;
	switch (event.GetId())
	{
	case ID_COPYFROM_B:
		slot = SLOT_A;
		slot2 = SLOT_B;
	case ID_COPYFROM_A:
		index = slot2 ? index_B : index_A;
		index = memoryCard[slot2]->GetFileIndex(index);
		if ((index != wxNOT_FOUND))
		{
			CopyDeleteSwitch(memoryCard[slot]->CopyFrom(*memoryCard[slot2], index), slot);
		}
		break;
	case ID_FIXCHECKSUM_A:
		slot = SLOT_A;
	case ID_FIXCHECKSUM_B:
		if (memoryCard[slot]->FixChecksums() && memoryCard[slot]->Save())
		{
			SuccessAlertT("The checksum was successfully fixed");
		}
		else
		{
			PanicAlert(E_SAVEFAILED);
		}
		break; 
	case ID_CONVERTTOGCI:
		fileName2 = "convert";
	case ID_SAVEIMPORT_A:
		slot = SLOT_A;
	case ID_SAVEIMPORT_B:
	{
		wxString fileName = wxFileSelector(
			_("Select a save file to import"),
			(strcmp(DefaultIOPath.c_str(), "/Users/GC") == 0)
				? StrToWxStr("")
				: StrToWxStr(DefaultIOPath),
			wxEmptyString, wxEmptyString,
			_("GameCube Savegame files(*.gci;*.gcs;*.sav)") + wxString(wxT("|*.gci;*.gcs;*.sav|")) +
			_("Native GCI files(*.gci)") + wxString(wxT("|*.gci|")) +
			_("MadCatz Gameshark files(*.gcs)") + wxString(wxT("|*.gcs|")) +
			_("Datel MaxDrive/Pro files(*.sav)") + wxString(wxT("|*.sav")),
			wxFD_OPEN | wxFD_FILE_MUST_EXIST, this);
		if (!fileName.empty() && !fileName2.empty())
		{
			wxString temp2 = wxFileSelector(_("Save GCI as..."),
				wxEmptyString, wxEmptyString, wxT(".gci"),
				_("GCI File(*.gci)") + wxString(_T("|*.gci")),
				wxFD_OVERWRITE_PROMPT|wxFD_SAVE, this);

			if (temp2.empty())
				break;

			fileName2 = WxStrToStr(temp2);
		}
		if (fileName.length() > 0)
		{
			CopyDeleteSwitch(memoryCard[slot]->ImportGci(WxStrToStr(fileName).c_str(), fileName2), slot);
		}
	}
	break;
	case ID_SAVEEXPORT_A:
		slot=SLOT_A;
		index = index_A;
	case ID_SAVEEXPORT_B:
		index = memoryCard[slot]->GetFileIndex(index);
		if (index != wxNOT_FOUND)
		{
			std::string gciFilename;
			if (!memoryCard[slot]->GCI_FileName(index, gciFilename))
			{
				PanicAlert("Invalid index");
				return;
			}
			wxString fileName = wxFileSelector(
				_("Export save as..."),
				StrToWxStr(DefaultIOPath),
				StrToWxStr(gciFilename), wxT(".gci"),
				_("Native GCI files(*.gci)") + wxString(wxT("|*.gci|")) +
				_("MadCatz Gameshark files(*.gcs)") + wxString(wxT("|*.gcs|")) +
				_("Datel MaxDrive/Pro files(*.sav)") + wxString(wxT("|*.sav")),
				wxFD_OVERWRITE_PROMPT|wxFD_SAVE, this);

			if (fileName.length() > 0)
			{
				if (!CopyDeleteSwitch(memoryCard[slot]->ExportGci(index, WxStrToStr(fileName).c_str(), ""), -1))
				{
					File::Delete(WxStrToStr(fileName));
				}
			}
		}
		break;
	case ID_EXPORTALL_A:
		slot=SLOT_A;
	case ID_EXPORTALL_B:
	{
		std::string path1, path2, mpath;
		mpath = WxStrToStr(m_MemcardPath[slot]->GetPath());
		SplitPath(mpath, &path1, &path2, NULL);
		path1 += path2;
		File::CreateDir(path1);
		if(PanicYesNoT("Warning: This will overwrite any existing saves that are in the folder:\n"
					"%s\nand have the same name as a file on your memcard\nContinue?", path1.c_str()))
		for (int i = 0; i < DIRLEN; i++)
		{
			CopyDeleteSwitch(memoryCard[slot]->ExportGci(i, NULL, path1), -1);
		}
		break;
	}
	case ID_DELETE_A:
		slot = SLOT_A;
		index = index_A;
	case ID_DELETE_B:
		index = memoryCard[slot]->GetFileIndex(index);
		if (index != wxNOT_FOUND)
		{
			CopyDeleteSwitch(memoryCard[slot]->RemoveFile(index), slot);
		}
		break;
	}
}
bool SCoreStartupParameter::AutoSetup(EBootBS2 _BootBS2)
{
	std::string Region(EUR_DIR);

	switch (_BootBS2)
	{
	case BOOT_DEFAULT:
		{
			bool bootDrive = cdio_is_cdrom(m_strFilename);
			// Check if the file exist, we may have gotten it from a --elf command line
			// that gave an incorrect file name
			if (!bootDrive && !File::Exists(m_strFilename))
			{
				PanicAlertT("The specified file \"%s\" does not exist", m_strFilename.c_str());
				return false;
			}

			std::string Extension;
			SplitPath(m_strFilename, nullptr, nullptr, &Extension);
			if (!strcasecmp(Extension.c_str(), ".gcm") ||
				!strcasecmp(Extension.c_str(), ".iso") ||
				!strcasecmp(Extension.c_str(), ".wbfs") ||
				!strcasecmp(Extension.c_str(), ".ciso") ||
				!strcasecmp(Extension.c_str(), ".gcz") ||
				bootDrive)
			{
				m_BootType = BOOT_ISO;
				DiscIO::IVolume* pVolume = DiscIO::CreateVolumeFromFilename(m_strFilename);
				if (pVolume == nullptr)
				{
					if (bootDrive)
						PanicAlertT("Could not read \"%s\".  "
								"There is no disc in the drive, or it is not a GC/Wii backup.  "
								"Please note that original Gamecube and Wii discs cannot be read "
								"by most PC DVD drives.", m_strFilename.c_str());
					else
						PanicAlertT("\"%s\" is an invalid GCM/ISO file, or is not a GC/Wii ISO.",
								m_strFilename.c_str());
					return false;
				}
				m_strName = pVolume->GetName();
				m_strUniqueID = pVolume->GetUniqueID();
				m_strRevisionSpecificUniqueID = pVolume->GetRevisionSpecificUniqueID();

				// Check if we have a Wii disc
				bWii = DiscIO::IsVolumeWiiDisc(pVolume);
				switch (pVolume->GetCountry())
				{
				case DiscIO::IVolume::COUNTRY_USA:
					bNTSC = true;
					Region = USA_DIR;
					break;

				case DiscIO::IVolume::COUNTRY_TAIWAN:
				case DiscIO::IVolume::COUNTRY_KOREA:
					// TODO: Should these have their own Region Dir?
				case DiscIO::IVolume::COUNTRY_JAPAN:
					bNTSC = true;
					Region = JAP_DIR;
					break;

				case DiscIO::IVolume::COUNTRY_EUROPE:
				case DiscIO::IVolume::COUNTRY_FRANCE:
				case DiscIO::IVolume::COUNTRY_ITALY:
				case DiscIO::IVolume::COUNTRY_RUSSIA:
					bNTSC = false;
					Region = EUR_DIR;
					break;

				default:
					if (PanicYesNoT("Your GCM/ISO file seems to be invalid (invalid country)."
								   "\nContinue with PAL region?"))
					{
						bNTSC = false;
						Region = EUR_DIR;
						break;
					}else return false;
				}

				delete pVolume;
			}
			else if (!strcasecmp(Extension.c_str(), ".elf"))
			{
				bWii = CBoot::IsElfWii(m_strFilename);
				Region = USA_DIR;
				m_BootType = BOOT_ELF;
				bNTSC = true;
			}
			else if (!strcasecmp(Extension.c_str(), ".dol"))
			{
				CDolLoader dolfile(m_strFilename);
				bWii = dolfile.IsWii();
				Region = USA_DIR;
				m_BootType = BOOT_DOL;
				bNTSC = true;
			}
			else if (!strcasecmp(Extension.c_str(), ".dff"))
			{
				bWii = true;
				Region = USA_DIR;
				bNTSC = true;
				m_BootType = BOOT_DFF;

				FifoDataFile *ddfFile = FifoDataFile::Load(m_strFilename, true);

				if (ddfFile)
				{
					bWii = ddfFile->GetIsWii();
					delete ddfFile;
				}
			}
			else if (DiscIO::CNANDContentManager::Access().GetNANDLoader(m_strFilename).IsValid())
			{
				const DiscIO::IVolume* pVolume = DiscIO::CreateVolumeFromFilename(m_strFilename);
				const DiscIO::INANDContentLoader& ContentLoader = DiscIO::CNANDContentManager::Access().GetNANDLoader(m_strFilename);

				if (ContentLoader.GetContentByIndex(ContentLoader.GetBootIndex()) == nullptr)
				{
					//WAD is valid yet cannot be booted. Install instead.
					u64 installed = DiscIO::CNANDContentManager::Access().Install_WiiWAD(m_strFilename);
					if (installed)
						SuccessAlertT("The WAD has been installed successfully");
					return false; //do not boot
				}

				switch (ContentLoader.GetCountry())
				{
				case DiscIO::IVolume::COUNTRY_USA:
					bNTSC = true;
					Region = USA_DIR;
					break;

				case DiscIO::IVolume::COUNTRY_TAIWAN:
				case DiscIO::IVolume::COUNTRY_KOREA:
					// TODO: Should these have their own Region Dir?
				case DiscIO::IVolume::COUNTRY_JAPAN:
					bNTSC = true;
					Region = JAP_DIR;
					break;

				case DiscIO::IVolume::COUNTRY_EUROPE:
				case DiscIO::IVolume::COUNTRY_FRANCE:
				case DiscIO::IVolume::COUNTRY_ITALY:
				case DiscIO::IVolume::COUNTRY_RUSSIA:
					bNTSC = false;
					Region = EUR_DIR;
					break;

				default:
					bNTSC = false;
					Region = EUR_DIR;
						break;
				}

				bWii = true;
				m_BootType = BOOT_WII_NAND;

				if (pVolume)
				{
					m_strName = pVolume->GetName();
					m_strUniqueID = pVolume->GetUniqueID();
					delete pVolume;
				}
				else
				{
					// null pVolume means that we are loading from nand folder (Most Likely Wii Menu)
					// if this is the second boot we would be using the Name and id of the last title
					m_strName.clear();
					m_strUniqueID.clear();
				}

				// Use the TitleIDhex for name and/or unique ID if launching from nand folder
				// or if it is not ascii characters (specifically sysmenu could potentially apply to other things)
				char titleidstr[17];
				snprintf(titleidstr, 17, "%016" PRIx64, ContentLoader.GetTitleID());

				if (!m_strName.length())
				{
					m_strName = titleidstr;
				}
				if (!m_strUniqueID.length())
				{
					m_strUniqueID = titleidstr;
				}

			}
			else
			{
				PanicAlertT("Could not recognize ISO file %s", m_strFilename.c_str());
				return false;
			}
		}
		break;

	case BOOT_BS2_USA:
		Region = USA_DIR;
		m_strFilename.clear();
		bNTSC = true;
		break;

	case BOOT_BS2_JAP:
		Region = JAP_DIR;
		m_strFilename.clear();
		bNTSC = true;
		break;

	case BOOT_BS2_EUR:
		Region = EUR_DIR;
		m_strFilename.clear();
		bNTSC = false;
		break;
	}

	// Setup paths
	CheckMemcardPath(SConfig::GetInstance().m_strMemoryCardA, Region, true);
	CheckMemcardPath(SConfig::GetInstance().m_strMemoryCardB, Region, false);
	m_strSRAM = File::GetUserPath(F_GCSRAM_IDX);
	if (!bWii)
	{
		m_strBootROM = File::GetUserPath(D_GCUSER_IDX) + DIR_SEP + Region + DIR_SEP GC_IPL;
		if (!File::Exists(m_strBootROM))
			m_strBootROM = File::GetSysDirectory() + GC_SYS_DIR + DIR_SEP + Region + DIR_SEP GC_IPL;

		if (!bHLE_BS2)
		{
			if (!File::Exists(m_strBootROM))
			{
				WARN_LOG(BOOT, "Bootrom file %s not found - using HLE.", m_strBootROM.c_str());
				bHLE_BS2 = true;
			}
		}
	}
	else if (bWii && !bHLE_BS2)
	{
		WARN_LOG(BOOT, "GC bootrom file will not be loaded for Wii mode.");
		bHLE_BS2 = true;
	}

	return true;
}
Exemple #19
0
/************************************************
 *	CHandsImage Constructor.
 ************************************************/
CHandsImage::CHandsImage(void)
{
	FBStringList list;
	FBString appPath = mSystem.ApplicationPath;
	SplitPath( appPath, list );

	appPath = "";
	for (int i=0; i<list.GetCount(); ++i)
	{
		appPath = appPath + list[i];
		appPath = appPath + "\\";
		if (strcmp(list[i], "bin") == 0) break;
	}

	FBString		szFullFilePath( appPath, HANDS_CTRL_IMAGE );
	FBString		szRegionDropPath( appPath, FINGER_CTRL_IMAGE );
	FBString		szRegionDropPath25( appPath, FINGER_CTRL_IMAGE_25 );
	FBString		szRegionDropPath50( appPath, FINGER_CTRL_IMAGE_50 );
	FBString		szRegionDropPath75( appPath, FINGER_CTRL_IMAGE_75 );
	FBString		szRegionDropPath100( appPath, FINGER_CTRL_IMAGE_100 );
	FBString		szRegionSelPath( appPath, SELECTED_CTRL_IMAGE );

	mHandsId = LoadTGA( szFullFilePath );
	mRegionDropId = LoadTGA( szRegionDropPath );
	mRegionDropId25		= LoadTGA( szRegionDropPath25 );
	mRegionDropId50		= LoadTGA( szRegionDropPath50 );
	mRegionDropId75		= LoadTGA( szRegionDropPath75 );
	mRegionDropId100	= LoadTGA( szRegionDropPath100 );
	mRegionSelectedId = LoadTGA( szRegionSelPath );

	mSelected = false;
	mReDraw = true;

	//-------------------
	//-- LEFT HAND
	FillHandLeftFinger( 0,	15, 95 );

	//-- index
	FillHandLeftFinger( 1,	50, 53 );
	FillHandLeftFinger( 2,	58, 43 );
	FillHandLeftFinger( 3,	68, 32 );
	//-- middle
	FillHandLeftFinger( 4,	36, 49 );
	FillHandLeftFinger( 5,	41, 35 );
	FillHandLeftFinger( 6,	45, 21 );
	//-- ring
	FillHandLeftFinger( 7,	25, 52 );
	FillHandLeftFinger( 8,	25, 38 );
	FillHandLeftFinger( 9,	25, 25 );
	//-- pinky
	FillHandLeftFinger( 10,		14, 57 );
	FillHandLeftFinger( 11,		10, 45 );
	FillHandLeftFinger( 12,		6, 34 );

	//-- thumb
	FillHandLeftFinger( 13,		58, 80 );
	FillHandLeftFinger( 14,		66, 74 );
	FillHandLeftFinger( 15,		76, 65 );

	//------------------------
	//-- RIGHT HAND
	FillHandRightFinger( 0,	15, 95 );

	//-- index
	FillHandRightFinger( 1,	50, 53 );
	FillHandRightFinger( 2,	58, 43 );
	FillHandRightFinger( 3,	68, 32 );
	//-- middle
	FillHandRightFinger( 4,	36, 49 );
	FillHandRightFinger( 5,	41, 35 );
	FillHandRightFinger( 6,	45, 21 );
	//-- ring
	FillHandRightFinger( 7,	25, 52 );
	FillHandRightFinger( 8,	25, 38 );
	FillHandRightFinger( 9,	25, 25 );
	//-- pinky
	FillHandRightFinger( 10,		14, 57 );
	FillHandRightFinger( 11,		10, 45 );
	FillHandRightFinger( 12,		6, 34 );

	//-- thumb
	FillHandRightFinger( 13,		58, 80 );
	FillHandRightFinger( 14,		66, 74 );
	FillHandRightFinger( 15,		76, 65 );

	//-- try to load finger position's from config file
	FBString		szConfigPath( appPath, CONFIG_FILENAME );
	LoadFingerConfig( szConfigPath );

	UpdateWeight();
}
Exemple #20
0
bool Texture3D::BeginLoad(Deserializer& source)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // In headless mode, do not actually load the texture, just return success
    if (!graphics_)
        return true;

    String texPath, texName, texExt;
    SplitPath(GetName(), texPath, texName, texExt);

    cache->ResetDependencies(this);

    loadParameters_ = new XMLFile(context_);
    if (!loadParameters_->Load(source))
    {
        loadParameters_.Reset();
        return false;
    }

    XMLElement textureElem = loadParameters_->GetRoot();
    XMLElement volumeElem = textureElem.GetChild("volume");
    XMLElement colorlutElem = textureElem.GetChild("colorlut");

    if (volumeElem)
    {
        String name = volumeElem.GetAttribute("name");

        String volumeTexPath, volumeTexName, volumeTexExt;
        SplitPath(name, volumeTexPath, volumeTexName, volumeTexExt);
        // If path is empty, add the XML file path
        if (volumeTexPath.Empty())
            name = texPath + name;

        loadImage_ = cache->GetTempResource<Image>(name);
        // Precalculate mip levels if async loading
        if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
            loadImage_->PrecalculateLevels();
        cache->StoreResourceDependency(this, name);
        return true;
    }
    else if (colorlutElem)
    {
        String name = colorlutElem.GetAttribute("name");

        String colorlutTexPath, colorlutTexName, colorlutTexExt;
        SplitPath(name, colorlutTexPath, colorlutTexName, colorlutTexExt);
        // If path is empty, add the XML file path
        if (colorlutTexPath.Empty())
            name = texPath + name;

        SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(name);
        loadImage_ = new Image(context_);
        if (!loadImage_->LoadColorLUT(*(file.Get())))
        {
            loadParameters_.Reset();
            loadImage_.Reset();
            return false;
        }
        // Precalculate mip levels if async loading
        if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
            loadImage_->PrecalculateLevels();
        cache->StoreResourceDependency(this, name);
        return true;
    }

    LOGERROR("Texture3D XML data for " + GetName() + " did not contain either volume or colorlut element");
    return false;
}
int OGRGRASSDataSource::Open( const char * pszNewName, int bUpdate,
                              int bTestOpen, int bSingleNewFileIn )
{
    VSIStatBuf  stat;
    
    CPLAssert( nLayers == 0 );
    
    pszName = CPLStrdup( pszNewName ); // Released by destructor

/* -------------------------------------------------------------------- */
/*      Do the given path contains 'vector' and 'head'?                 */
/* -------------------------------------------------------------------- */
    if ( strstr(pszName,"vector") == NULL || strstr(pszName,"head") == NULL )
    {
        if( !bTestOpen )
	{
            CPLError( CE_Failure, CPLE_AppDefined,
                 "%s is not GRASS vector, access failed.\n", pszName );
	}
	return FALSE;
    }
    
/* -------------------------------------------------------------------- */
/*      Is the given a regular file?                                    */
/* -------------------------------------------------------------------- */
    if( CPLStat( pszName, &stat ) != 0 || !VSI_ISREG(stat.st_mode) )
    {
        if( !bTestOpen )
	{
            CPLError( CE_Failure, CPLE_AppDefined,
                 "%s is not GRASS vector, access failed.\n", pszName );
	}

        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Parse datasource name                                           */
/* -------------------------------------------------------------------- */
    if ( !SplitPath(pszName, &pszGisdbase, &pszLocation, 
		    &pszMapset, &pszMap) ) 
    {
        if( !bTestOpen )
	{
            CPLError( CE_Failure, CPLE_AppDefined,
                      "%s is not GRASS datasource name, access failed.\n", 
		      pszName );
	}
	return FALSE;
    }
			
    CPLDebug ( "GRASS", "Gisdbase: %s", pszGisdbase );
    CPLDebug ( "GRASS", "Location: %s", pszLocation );
    CPLDebug ( "GRASS", "Mapset: %s", pszMapset );
    CPLDebug ( "GRASS", "Map: %s", pszMap );

/* -------------------------------------------------------------------- */
/*      Init GRASS library                                              */
/* -------------------------------------------------------------------- */
    // GISBASE is path to the directory where GRASS is installed,
    // it is necessary because there are database drivers.
    if ( !getenv( "GISBASE" ) ) {
        static char* gisbaseEnv = NULL;
        const char *gisbase = GRASS_GISBASE;
        CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: GISBASE "
                "enviroment variable was not set, using:\n%s", gisbase );
        char buf[2000];
        snprintf ( buf, sizeof(buf), "GISBASE=%s", gisbase );
        buf[sizeof(buf)-1] = '\0';

        CPLFree(gisbaseEnv);
        gisbaseEnv = CPLStrdup ( buf );
        putenv( gisbaseEnv );
    }

    // Don't use GISRC file and read/write GRASS variables 
    // (from location G_VAR_GISRC) to memory only.
    G_set_gisrc_mode ( G_GISRC_MODE_MEMORY );

    // Init GRASS libraries (required). G_no_gisinit() doesn't check 
    // write permissions for mapset compare to G_gisinit()
    G_no_gisinit();  

    // Set error function
    G_set_error_routine ( (GrassErrorHandler) Grass2OGRErrorHook );

/* -------------------------------------------------------------------- */
/*      Set GRASS variables                                             */
/* -------------------------------------------------------------------- */
     G__setenv( "GISDBASE", pszGisdbase );
     G__setenv( "LOCATION_NAME", pszLocation );
     G__setenv( "MAPSET", pszMapset); 
     G_reset_mapsets();
     G_add_mapset_to_search_path ( pszMapset );

/* -------------------------------------------------------------------- */
/*      Open GRASS vector map                                           */
/* -------------------------------------------------------------------- */
    Vect_set_fatal_error ( GV_FATAL_PRINT ); // Print error and continue
    Vect_set_open_level (2);
    int level = Vect_open_old ( &map, pszMap, pszMapset);

    if ( level < 2 ) {
        CPLError( CE_Failure, CPLE_AppDefined,
                 "Cannot open GRASS vector %s on level 2.\n", pszName );
	return FALSE;
    }

    CPLDebug ( "GRASS", "Num lines = %d", Vect_get_num_lines(&map) );
    
/* -------------------------------------------------------------------- */
/*      Build a list of layers.                                         */
/* -------------------------------------------------------------------- */
    int ncidx = Vect_cidx_get_num_fields ( &map );
    CPLDebug ( "GRASS", "Num layers = %d", ncidx );

    for ( int i = 0; i < ncidx; i++ ) {
	// Create the layer object
	OGRGRASSLayer       *poLayer;

        poLayer = new OGRGRASSLayer( i, &map );
	
        // Add layer to data source layer list
	papoLayers = (OGRGRASSLayer **)
	    CPLRealloc( papoLayers,  sizeof(OGRGRASSLayer *) * (nLayers+1) );
	papoLayers[nLayers++] = poLayer;
    }
    
    bOpened = TRUE;
    
    return TRUE;
}
NS_IMETHODIMP
nsLocalFile::GetRelativeDescriptor(nsIFile* aFromFile, nsACString& aResult)
{
  if (NS_WARN_IF(!aFromFile)) {
    return NS_ERROR_INVALID_ARG;
  }

  //
  // aResult will be UTF-8 encoded
  //

  nsresult rv;
  aResult.Truncate(0);

  nsAutoString thisPath, fromPath;
  nsAutoTArray<char16_t*, 32> thisNodes;
  nsAutoTArray<char16_t*, 32> fromNodes;

  rv = GetPath(thisPath);
  if (NS_FAILED(rv)) {
    return rv;
  }
  rv = aFromFile->GetPath(fromPath);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // get raw pointer to mutable string buffer
  char16_t* thisPathPtr;
  thisPath.BeginWriting(thisPathPtr);
  char16_t* fromPathPtr;
  fromPath.BeginWriting(fromPathPtr);

  SplitPath(thisPathPtr, thisNodes);
  SplitPath(fromPathPtr, fromNodes);

  size_t nodeIndex;
  for (nodeIndex = 0;
       nodeIndex < thisNodes.Length() && nodeIndex < fromNodes.Length();
       ++nodeIndex) {
#ifdef XP_WIN
    if (_wcsicmp(char16ptr_t(thisNodes[nodeIndex]),
                 char16ptr_t(fromNodes[nodeIndex]))) {
      break;
    }
#else
    if (nsCRT::strcmp(thisNodes[nodeIndex], fromNodes[nodeIndex])) {
      break;
    }
#endif
  }

  size_t branchIndex = nodeIndex;
  for (nodeIndex = branchIndex; nodeIndex < fromNodes.Length(); ++nodeIndex) {
    aResult.AppendLiteral("../");
  }
  for (nodeIndex = branchIndex; nodeIndex < thisNodes.Length(); ++nodeIndex) {
    NS_ConvertUTF16toUTF8 nodeStr(thisNodes[nodeIndex]);
    aResult.Append(nodeStr);
    if (nodeIndex + 1 < thisNodes.Length()) {
      aResult.Append('/');
    }
  }

  return NS_OK;
}
Exemple #23
0
void CGameListCtrl::ScanForISOs()
{
	ClearIsoFiles();

	// Load custom game titles from titles.txt
	// http://www.gametdb.com/Wii/Downloads
	std::unordered_map<std::string, std::string> custom_title_map;
	std::ifstream titlestxt;
	OpenFStream(titlestxt, File::GetUserPath(D_LOAD_IDX) + "titles.txt", std::ios::in);

	if (!titlestxt.is_open())
		OpenFStream(titlestxt, File::GetUserPath(D_LOAD_IDX) + "wiitdb.txt", std::ios::in);

	if (titlestxt.is_open())
	{
		std::string line;
		while (!titlestxt.eof() && std::getline(titlestxt, line))
		{
			const size_t equals_index = line.find('=');
			if (equals_index != std::string::npos)
				custom_title_map.emplace(StripSpaces(line.substr(0, equals_index)),
			                             StripSpaces(line.substr(equals_index + 1)));
		}
		titlestxt.close();
	}

	std::vector<std::string> Extensions;

	if (SConfig::GetInstance().m_ListGC)
		Extensions.push_back(".gcm");
	if (SConfig::GetInstance().m_ListWii || SConfig::GetInstance().m_ListGC)
	{
		Extensions.push_back(".iso");
		Extensions.push_back(".ciso");
		Extensions.push_back(".gcz");
		Extensions.push_back(".wbfs");
	}
	if (SConfig::GetInstance().m_ListWad)
		Extensions.push_back(".wad");
	if (SConfig::GetInstance().m_ListElfDol)
	{
		Extensions.push_back(".dol");
		Extensions.push_back(".elf");
	}

	auto rFilenames = DoFileSearch(Extensions, SConfig::GetInstance().m_ISOFolder, SConfig::GetInstance().m_RecursiveISOFolder);

	if (rFilenames.size() > 0)
	{
		wxProgressDialog dialog(
			_("Scanning for ISOs"),
			_("Scanning..."),
			(int)rFilenames.size() - 1,
			this,
			wxPD_APP_MODAL |
			wxPD_AUTO_HIDE |
			wxPD_CAN_ABORT |
			wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME |
			wxPD_SMOOTH // - makes updates as small as possible (down to 1px)
			);

		for (u32 i = 0; i < rFilenames.size(); i++)
		{
			std::string FileName;
			SplitPath(rFilenames[i], nullptr, &FileName, nullptr);

			// Update with the progress (i) and the message
			dialog.Update(i, wxString::Format(_("Scanning %s"),
				StrToWxStr(FileName)));
			if (dialog.WasCancelled())
				break;

			auto iso_file = std::make_unique<GameListItem>(rFilenames[i], custom_title_map);

			if (iso_file->IsValid())
			{
				bool list = true;

				switch(iso_file->GetPlatform())
				{
					case DiscIO::IVolume::WII_DISC:
						if (!SConfig::GetInstance().m_ListWii)
							list = false;
						break;
					case DiscIO::IVolume::WII_WAD:
						if (!SConfig::GetInstance().m_ListWad)
							list = false;
						break;
					case DiscIO::IVolume::ELF_DOL:
						if (!SConfig::GetInstance().m_ListElfDol)
							list = false;
						break;
					default:
						if (!SConfig::GetInstance().m_ListGC)
							list = false;
						break;
				}

				switch(iso_file->GetCountry())
				{
					case DiscIO::IVolume::COUNTRY_AUSTRALIA:
						if (!SConfig::GetInstance().m_ListAustralia)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_EUROPE:
						if (!SConfig::GetInstance().m_ListPal)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_FRANCE:
						if (!SConfig::GetInstance().m_ListFrance)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_GERMANY:
						if (!SConfig::GetInstance().m_ListGermany)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_ITALY:
						if (!SConfig::GetInstance().m_ListItaly)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_JAPAN:
						if (!SConfig::GetInstance().m_ListJap)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_KOREA:
						if (!SConfig::GetInstance().m_ListKorea)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_NETHERLANDS:
						if (!SConfig::GetInstance().m_ListNetherlands)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_RUSSIA:
						if (!SConfig::GetInstance().m_ListRussia)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_SPAIN:
						if (!SConfig::GetInstance().m_ListSpain)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_TAIWAN:
						if (!SConfig::GetInstance().m_ListTaiwan)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_USA:
						if (!SConfig::GetInstance().m_ListUsa)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_WORLD:
						if (!SConfig::GetInstance().m_ListWorld)
							list = false;
						break;
					case DiscIO::IVolume::COUNTRY_UNKNOWN:
					default:
						if (!SConfig::GetInstance().m_ListUnknown)
							list = false;
						break;
				}

				if (list)
					m_ISOFiles.push_back(iso_file.release());
			}
		}
	}

	if (SConfig::GetInstance().m_ListDrives)
	{
		const std::vector<std::string> drives = cdio_get_devices();

		for (const auto& drive : drives)
		{
			auto gli = std::make_unique<GameListItem>(drive, custom_title_map);

			if (gli->IsValid())
				m_ISOFiles.push_back(gli.release());
		}
	}

	std::sort(m_ISOFiles.begin(), m_ISOFiles.end());
}