// Copy file contents bool FileSpecifier::CopyContents(FileSpecifier &source_name) { err = 0; OpenedFile src, dst; if (source_name.Open(src)) { Delete(); if (Open(dst, true)) { const int BUFFER_SIZE = 1024; uint8 buffer[BUFFER_SIZE]; int32 length = 0; src.GetLength(length); while (length && err == 0) { int32 count = length > BUFFER_SIZE ? BUFFER_SIZE : length; if (src.Read(count, buffer)) { if (!dst.Write(count, buffer)) err = dst.GetError(); } else err = src.GetError(); length -= count; } } } else err = source_name.GetError(); if (err) Delete(); return err == 0; }
void WadImageCache::save_cache() { if (!m_cache_dirty) return; InfoTree pt; for (cache_iter_t it = m_used.begin(); it != m_used.end(); ++it) { std::string name = it->second.first; WadImageDescriptor desc = boost::tuples::get<0>(it->first); pt.put(name + ".path", desc.file.GetPath()); pt.put(name + ".checksum", desc.checksum); pt.put(name + ".index", desc.index); pt.put(name + ".tag", desc.tag); pt.put(name + ".width", boost::tuples::get<1>(it->first)); pt.put(name + ".height", boost::tuples::get<2>(it->first)); pt.put(name + ".filesize", it->second.second); } FileSpecifier info; info.SetToImageCacheDir(); info.AddPart("Cache.ini"); try { pt.save_ini(info); m_cache_dirty = false; } catch (InfoTree::ini_error e) { logError("Could not save image cache to %s (%s)", info.GetPath(), e.what()); return; } }
static bool confirm_save_choice(FileSpecifier & file) { // If the file doesn't exist, everything is alright if (!file.Exists()) return true; // Construct message char name[256]; file.GetName(name); char message[512]; sprintf(message, "'%s' already exists.", name); // Create dialog dialog d; vertical_placer *placer = new vertical_placer; placer->dual_add(new w_static_text(message), d); placer->dual_add(new w_static_text("Ok to overwrite?"), d); placer->add(new w_spacer(), true); horizontal_placer *button_placer = new horizontal_placer; w_button *default_button = new w_button("YES", dialog_ok, &d); button_placer->dual_add(default_button, d); button_placer->dual_add(new w_button("NO", dialog_cancel, &d), d); placer->add(button_placer, true); d.activate_widget(default_button); d.set_widget_placer(placer); // Run dialog return d.run() == 0; }
void operator() (const std::string& arg) const { if (!NetAllowSavingLevel()) { screen_printf("Level saving disabled"); return; } std::string filename = arg; if (filename == "") { if (last_level != "") filename = last_level; else { filename = mac_roman_to_utf8(static_world->level_name); if (!boost::algorithm::ends_with(filename, ".sceA")) filename += ".sceA"; } } else { if (!boost::algorithm::ends_with(filename, ".sceA")) filename += ".sceA"; } last_level = filename; FileSpecifier fs; fs.SetToLocalDataDir(); fs += filename; if (export_level(fs)) screen_printf("Saved %s", utf8_to_mac_roman(fs.GetPath()).c_str()); else screen_printf("An error occurred while saving the level"); }
bool XML_Loader_SDL::ParseFile(FileSpecifier &file_name) { // Open file OpenedFile file; if (file_name.Open(file)) { printf ( "Parsing: %s\n", file_name.GetPath() ); // Get file size and allocate buffer file.GetLength(data_size); data = new char[data_size]; // In case there were errors... file_name.GetName(FileName); // Read and parse file if (file.Read(data_size, data)) { if (!DoParse()) { fprintf(stderr, "There were parsing errors in configuration file %s\n", FileName); } } // Delete buffer delete[] data; data = NULL; return true; } else { printf ( "Couldn't open: %s\n", file_name.GetPath() ); } return false; }
bool save_game( void) { pause_game(); show_cursor(); /* Translate the name, and display the dialog */ FileSpecifier SaveFile; get_current_saved_game_name(SaveFile); char GameName[256]; SaveFile.GetName(GameName); char Prompt[256]; // Must allow the sound to play in the background bool success = SaveFile.WriteDialogAsync( _typecode_savegame, getcstr(Prompt, strPROMPTS, _save_game_prompt), GameName); if (success) success = save_game_file(SaveFile); hide_cursor(); resume_game(); return success; }
SDL_Surface* QuickSaveImageCache::get(std::string image_name) { std::map<std::string, cache_iter_t>::iterator it = m_images.find(image_name); if (it != m_images.end()) { // found it: move to front of list m_used.splice(m_used.begin(), m_used, it->second); return it->second->second; } // didn't find: load image FileSpecifier f; f.SetToQuickSavesDir(); f.AddPart(image_name + ".sgaA"); WadImageDescriptor desc; desc.file = f; desc.checksum = 0; desc.index = SAVE_GAME_METADATA_INDEX; desc.tag = SAVE_IMG_TAG; SDL_Surface *img = WadImageCache::instance()->get_image(desc, PREVIEW_WIDTH, PREVIEW_HEIGHT); if (img) { m_used.push_front(cache_pair_t(image_name, img)); m_images[image_name] = m_used.begin(); // enforce maximum cache size if (m_used.size() > k_max_items) { cache_iter_t lru = m_used.end(); --lru; m_images.erase(lru->first); SDL_FreeSurface(lru->second); m_used.pop_back(); } } return img; }
bool XML_Loader_SDL::ParseDirectory(FileSpecifier &dir) { // Get sorted list of files in directory printf ( "Looking in %s\n", dir.GetPath() ); vector<dir_entry> de; if (!dir.ReadDirectory(de)) { return false; } sort(de.begin(), de.end()); // Parse each file vector<dir_entry>::const_iterator i, end = de.end(); for (i=de.begin(); i!=end; i++) { if (i->is_directory) { continue; } if (i->name[i->name.length() - 1] == '~') { continue; } // people stick Lua scripts in Scripts/ if (boost::algorithm::ends_with(i->name, ".lua")) { continue; } // Construct full path name FileSpecifier file_name = dir + i->name; // Parse file ParseFile(file_name); } return true; }
bool FileFinder::Find(DirectorySpecifier &dir, Typecode type, bool recursive) { // Get list of entries in directory vector<dir_entry> entries; if (!dir.ReadDirectory(entries)) return false; sort(entries.begin(), entries.end()); // Iterate through entries vector<dir_entry>::const_iterator i, end = entries.end(); for (i = entries.begin(); i != end; i++) { // Construct full specifier of file/dir FileSpecifier file = dir + i->name; if (i->is_directory) { // Recurse into directory if (recursive) if (Find(file, type, recursive)) return true; } else { // Check file type and call found() function if (type == WILDCARD_TYPE || type == file.GetType()) if (found(file)) return true; } } return false; }
bool PluginLoader::ParsePlugin(FileSpecifier& file_name) { OpenedFile file; if (file_name.Open(file)) { int32 data_size; file.GetLength(data_size); m_data.resize(data_size); if (file.Read(data_size, &m_data[0])) { file_name.ToDirectory(current_plugin_directory); char name[256]; current_plugin_directory.GetName(name); m_name = name; if (!DoParse()) { logError1("There were parsing errors in %s Plugin.xml\n", m_name.c_str()); } } m_data.clear(); return true; } return false; }
void rewind_recording( void) { if(replay.game_is_being_recorded) { /* This is unnecessary, because it is called from reset_player_queues, */ /* which is always called from revert_game */ /* FilmFile.SetLength(sizeof(recording_header)); FilmFile.SetPosition(sizeof(recording_header)); */ // Alternative that does not use "SetLength", but instead creates and re-creates the file. FilmFile.SetPosition(0); byte Header[SIZEOF_recording_header]; FilmFile.Read(SIZEOF_recording_header,Header); FilmFile.Close(); FilmFileSpec.Delete(); FilmFileSpec.Create(_typecode_film); FilmFileSpec.Open(FilmFile,true); FilmFile.Write(SIZEOF_recording_header,Header); // Use the packed length here!!! replay.header.length= SIZEOF_recording_header; } }
bool LoadModel_Studio(FileSpecifier& Spec, Model3D& Model) { ModelPtr = &Model; Model.Clear(); if (DBOut) { // Name buffer const int BufferSize = 256; char Buffer[BufferSize]; Spec.GetName(Buffer); fprintf(DBOut,"Loading 3D Studio Max model file %s\n",Buffer); } OpenedFile OFile; if (!Spec.Open(OFile)) { if (DBOut) fprintf(DBOut,"ERROR opening the file\n"); return false; } ChunkHeaderData ChunkHeader; if (!ReadChunkHeader(OFile,ChunkHeader)) return false; if (ChunkHeader.ID != MASTER) { if (DBOut) fprintf(DBOut,"ERROR: not a 3DS Max model file\n"); return false; } if (!ReadContainer(OFile,ChunkHeader,ReadMaster)) return false; return (!Model.Positions.empty() && !Model.VertIndices.empty()); }
void WadImageCache::delete_storage_for_name(std::string& name) const { FileSpecifier file; file.SetToImageCacheDir(); file.AddPart(name); file.Delete(); }
bool OGL_LoadScreen::Start() { // load the image FileSpecifier File; if (path.size() == 0) return use = false; if (!File.SetNameWithPath(path.c_str())) return use = false; if (!image.LoadFromFile(File, ImageLoader_Colors, 0)) return use = false; if (!blitter.Load(image)) return use = false; int screenWidth, screenHeight; MainScreenSize(screenWidth, screenHeight); bound_screen(); // the true width/height int imageWidth = static_cast<int>(image.GetWidth() * image.GetVScale()); int imageHeight = static_cast<int>(image.GetHeight() * image.GetUScale()); if (scale) { if (stretch) { m_dst.w = screenWidth; m_dst.h = screenHeight; } else if (imageWidth / imageHeight > screenWidth / screenHeight) { m_dst.w = screenWidth; m_dst.h = imageHeight * screenWidth / imageWidth; } else { m_dst.w = imageWidth * screenHeight / imageHeight; m_dst.h = screenHeight; } } else { m_dst.w = imageWidth; m_dst.h = imageHeight; } m_dst.x = (screenWidth - m_dst.w) / 2; m_dst.y = (screenHeight - m_dst.h) / 2; x_offset = m_dst.x; y_offset = m_dst.y; x_scale = m_dst.w / (double) imageWidth; y_scale = m_dst.h / (double) imageHeight; OGL_ClearScreen(); Progress(0); return use = true; }
static void load_mmls(const Plugin& plugin, XML_Loader_SDL& loader) { ScopedSearchPath ssp(plugin.directory); for (std::vector<std::string>::const_iterator it = plugin.mmls.begin(); it != plugin.mmls.end(); ++it) { FileSpecifier file; file.SetNameWithPath(it->c_str()); loader.ParseFile(file); } }
// Search for level script and then run it void FindMovieInScript(int LevelIndex) { // Find the pointer to the current script CurrScriptPtr = NULL; for (vector<LevelScriptHeader>::iterator ScriptIter = LevelScripts.begin(); ScriptIter < LevelScripts.end(); ScriptIter++) { if (ScriptIter->Level == LevelIndex) { CurrScriptPtr = &(*ScriptIter); // Iterator to pointer break; } } if (!CurrScriptPtr) { return; } for (unsigned k=0; k<CurrScriptPtr->Commands.size(); k++) { LevelScriptCommand& Cmd = CurrScriptPtr->Commands[k]; switch(Cmd.Type) { case LevelScriptCommand::Movie: { MovieFileExists = MovieFile.SetNameWithPath(&Cmd.FileSpec[0]); // Set the size only if there was a movie file here if (MovieFileExists) { MovieSize = Cmd.Size; } } break; } } }
bool physics_file_is_m1(void) { bool m1_physics = false; // check for M1 physics OpenedFile PhysicsFile; short SavedType, SavedError = get_game_error(&SavedType); if (PhysicsFileSpec.Open(PhysicsFile)) { uint32 tag = SDL_ReadBE32(PhysicsFile.GetRWops()); switch (tag) { case M1_MONSTER_PHYSICS_TAG: case M1_EFFECTS_PHYSICS_TAG: case M1_PROJECTILE_PHYSICS_TAG: case M1_PHYSICS_PHYSICS_TAG: case M1_WEAPONS_PHYSICS_TAG: m1_physics = true; break; default: break; } PhysicsFile.Close(); } set_game_error(SavedType, SavedError); return m1_physics; }
static const char *locate_font(const std::string& path) { builtin_fonts_t::iterator j = builtin_fonts.find(path); if (j != builtin_fonts.end() || path == "") { return path.c_str(); } else { static FileSpecifier file; if (file.SetNameWithPath(path.c_str())) return file.GetPath(); else return ""; } }
bool find_replay_to_use(bool ask_user, FileSpecifier &file) { if (ask_user) { return file.ReadDialog(_typecode_film); } else return get_recording_filedesc(file); }
// Analogous to 'save_game()', but does not present any dialog to the user, and reports the results // using screen_printf(). If inOverwriteRecent is set, it will save over the most recently saved // or restored game (if possible). If inOverwriteRecent is not set, or if there is no recent game // to save over, it will pick a new, nonconflicting filename and save to it. // Returns whether save was successful. bool save_game_full_auto(bool inOverwriteRecent) { bool createNewFile = !inOverwriteRecent; FileSpecifier theRecentSavedGame; get_current_saved_game_name(theRecentSavedGame); char theSavedGameName[256]; // XXX // If we're supposed to overwrite, change our minds if we seem to have no 'existing file'. if(!createNewFile) { theRecentSavedGame.GetName(theSavedGameName); if(strcmp(theSavedGameName, TS_GetCString(strFILENAMES, filenameDEFAULT_SAVE_GAME)) == 0) createNewFile = true; } // Make up a filename (currently based on level name) if(createNewFile) { if(strncpy_filename_friendly(theSavedGameName, static_world->level_name, kMaxFilenameChars) <= 0) strcpy(theSavedGameName, "Automatic Save"); DirectorySpecifier theDirectory; theRecentSavedGame.ToDirectory(theDirectory); theRecentSavedGame.FromDirectory(theDirectory); #if defined(mac) || defined(SDL_RFORK_HACK) // Note: SetName() currently ignores the 'type' argument, so I feel // little compulsion to try to figure it out. theRecentSavedGame.SetName(theSavedGameName,NONE); #else theRecentSavedGame.AddPart(theSavedGameName); #endif } FileSpecifier theOutputFile; if(createNewFile) make_nonconflicting_filename_variant(theRecentSavedGame, theOutputFile, kMaxFilenameChars); else theOutputFile = theRecentSavedGame; bool successfulSave = save_game_file(theOutputFile); theOutputFile.GetName(theSavedGameName); if(successfulSave) { screen_printf("%s saved game '%s'", createNewFile ? "Created new" : "Replaced existing", theSavedGameName); // play a sound? } else { screen_printf("Unable to save game as '%s'", theSavedGameName); // play a sound? } return successfulSave; }
SDL_Surface *WadImageCache::image_from_name(std::string& name) const { FileSpecifier file; file.SetToImageCacheDir(); file.AddPart(name); OpenedFile of; if (!file.Open(of)) return NULL; #ifdef HAVE_SDL_IMAGE SDL_Surface *img = IMG_Load_RW(of.GetRWops(), 0); #else SDL_Surface *img = SDL_LoadBMP_RW(of.GetRWops(), 0); #endif return img; }
void WadImageCache::initialize_cache() { FileSpecifier info; info.SetToImageCacheDir(); info.AddPart("Cache.ini"); if (!info.Exists()) return; InfoTree pt; try { pt = InfoTree::load_ini(info); } catch (InfoTree::ini_error e) { logError("Could not read image cache from %s (%s)", info.GetPath(), e.what()); } for (InfoTree::iterator it = pt.begin(); it != pt.end(); ++it) { std::string name = it->first; InfoTree ptc = it->second; WadImageDescriptor desc; std::string path; ptc.read("path", path); desc.file = FileSpecifier(path); ptc.read("checksum", desc.checksum); ptc.read("index", desc.index); ptc.read("tag", desc.tag); int width = 0; ptc.read("width", width); int height = 0; ptc.read("height", height); size_t filesize = 0; ptc.read("filesize", filesize); cache_key_t key = cache_key_t(desc, width, height); cache_value_t val = cache_value_t(name, filesize); m_used.push_front(cache_pair_t(key, val)); m_cacheinfo[key] = m_used.begin(); m_cachesize += filesize; } }
void add_finishing_touches_to_save_file(FileSpecifier &File) // FileDesc *file) { short refnum; unsigned char name[64+1]; OSErr err; FSSpec *SpecPtr = &File.GetSpec(); FInfo finder_info; err = FSpGetFInfo((FSSpec *)SpecPtr, &finder_info); if (err != noErr) return; FSpCreateResFile(SpecPtr, finder_info.fdCreator, finder_info.fdType, smSystemScript); if (ResError() != noErr) return; /* Save the STR resource that tells us what our application name is. */ refnum= FSpOpenResFile(&File.GetSpec(), fsWrPerm); // resource_file_ref= FSpOpenResFile((FSSpec *) file, fsWrPerm); if (refnum < 0) return; Handle resource; /* Add in the overhead thumbnail. */ add_overhead_thumbnail(File); /* Add the application name resource.. */ getpstr(name, strFILENAMES, filenameMARATHON_NAME); // add_application_name_to_fsspec((FileDesc *) file, name); // LP: copied out of files_macintosh.c -- add_application_name_to_fsspec(); // this is the only place that uses this code /* Add in the application name */ err= PtrToHand(name, &resource, name[0]+1); assert(!err && resource); AddResource(resource, 'STR ', -16396, "\p"); ReleaseResource(resource); CloseResFile(refnum); // End copying }
FileSpecifier GetPath() { FileSpecifier dir = m_list_w->get_file(); std::string base; std::string part; dir.SplitPath(base, part); std::string filename = GetFilename(); if (part == filename) { dir = base; } if (m_extension && !boost::algorithm::ends_with(filename, m_extension)) { filename += m_extension; } dir.AddPart(filename); return dir; }
bool XML_ShaderParser::HandleAttribute(const char *Tag, const char *Value) { if(StringsEqual(Tag,"name")) { _name = Value; return true; } else if(StringsEqual(Tag,"vert")) { _vert.SetNameWithPath(Value); return true; } else if(StringsEqual(Tag,"frag")) { _frag.SetNameWithPath(Value); return true; } else if(StringsEqual(Tag,"passes")) { return ReadInt16Value(Value,_passes); } UnrecognizedTag(); return true; };
// This tries to find a filename (in the same directory as inBaseName) based on 'inBaseName' but that is not yet used. // The current logic tries inBaseName first, then 'inBaseName 2', then 'inBaseName 3', and so on. // The resulting name will have no more than inMaxNameLength actual characters. // Returns whether it was successful (the current logic either returns true or loops forever; fortunately, the // probability of looping forever is really, REALLY tiny; the directory would have to contain every possible variant). static bool make_nonconflicting_filename_variant(/*const*/ FileSpecifier& inBaseName, FileSpecifier& outNonconflictingName, size_t inMaxNameLength) { FileSpecifier theNameToTry; DirectorySpecifier theDirectory; inBaseName.ToDirectory(theDirectory); char theBaseNameString[256]; // XXX I don't like this, but the SDL code already imposes this maxlen throughout. inBaseName.GetName(theBaseNameString); size_t theBaseNameLength = strlen(theBaseNameString); char theNameToTryString[256]; char theVariantSuffix[32]; // way more than enough unsigned int theVariant = 0; size_t theSuffixLength; size_t theBaseNameLengthToUse; bool theVariantIsAcceptable = false; while(!theVariantIsAcceptable) { theVariant++; if(theVariant == 1) { theVariantSuffix[0] = '\0'; theSuffixLength = 0; } else { theSuffixLength = sprintf(theVariantSuffix, " %d", theVariant); } assert(theSuffixLength <= inMaxNameLength); if(theSuffixLength + theBaseNameLength > inMaxNameLength) theBaseNameLengthToUse = inMaxNameLength - theSuffixLength; else theBaseNameLengthToUse = theBaseNameLength; sprintf(theNameToTryString, "%.*s%s", (int) theBaseNameLengthToUse, theBaseNameString, theVariantSuffix); theNameToTry.FromDirectory(theDirectory); #if defined(mac) || defined(SDL_RFORK_HACK) // Note: SetName() currently ignores the 'type' argument, so I feel // little compulsion to try to figure it out. theNameToTry.SetName(theNameToTryString,NONE); #else theNameToTry.AddPart(theNameToTryString); #endif if(!theNameToTry.Exists()) theVariantIsAcceptable = true; } if(theVariantIsAcceptable) { outNonconflictingName = theNameToTry; } return theVariantIsAcceptable; }
bool PluginLoader::ParseDirectory(FileSpecifier& dir) { std::vector<dir_entry> de; if (!dir.ReadDirectory(de)) { return false; } for (std::vector<dir_entry>::const_iterator it = de.begin(); it != de.end(); ++it) { FileSpecifier file = dir + it->name; if (it->name == "Plugin.xml") { ParsePlugin(file); } else if (it->is_directory && it->name[0] != '.') { ParseDirectory(file); } #ifdef HAVE_ZZIP else if (algo::ends_with(it->name, ".zip") || algo::ends_with(it->name, ".ZIP")) { // search it for a Plugin.xml file ZZIP_DIR* zzipdir = zzip_dir_open(file.GetPath(), 0); if (zzipdir) { ZZIP_DIRENT dirent; while (zzip_dir_read(zzipdir, &dirent)) { if (algo::ends_with(dirent.d_name, "Plugin.xml")) { std::string archive = file.GetPath(); FileSpecifier file_name = FileSpecifier(archive.substr(0, archive.find_last_of('.'))) + dirent.d_name; ParsePlugin(file_name); } } zzip_dir_close(zzipdir); } } #endif } return true; }
static bool get_default_spec(FileSpecifier &file, const string &name) { vector<DirectorySpecifier>::const_iterator i = data_search_path.begin(), end = data_search_path.end(); while (i != end) { file = *i + name; if (file.Exists()) return true; i++; } return false; }
static void dialog_export(void *arg) { dialog *d = static_cast<dialog *>(arg); w_saves *saves_w = static_cast<w_saves *>(d->get_widget_by_id(iDIALOG_SAVES_W)); QuickSave sel = saves_w->selected_save(); std::string name = sel.name; if (!name.length()) name = sel.level_name; FileSpecifier dstFile; dstFile.SetToSavedGamesDir(); dstFile += "unused.sgaA"; char prompt[256]; if (dstFile.WriteDialog(_typecode_savegame, getcstr(prompt, strPROMPTS, _save_replay_prompt), utf8_to_mac_roman(name).c_str())) { dstFile.CopyContents(sel.save_file); int error = dstFile.GetError(); if (error) alert_user(infoError, strERRORS, fileError, error); } }
bool FileFinder::Find(DirectorySpecifier &dir, Typecode type, bool recursive) { // Get list of entries in directory vector<dir_entry> entries; if (!dir.ReadDirectory(entries)) { return false; } sort(entries.begin(), entries.end()); // Iterate through entries vector<dir_entry>::const_iterator i, end = entries.end(); for (i = entries.begin(); i != end; i++) { // Construct full specifier of file/dir FileSpecifier file = dir + i->name; // DJB Skip our texture directories if ( dir.GetPathString().find ( "SpriteTextures" ) != string::npos || dir.GetPathString().find ( "TTEP" ) != string::npos ) { // Don't go down these paths return false; } if (i->is_directory) { // Recurse into directory if (recursive) { if (Find(file, type, recursive)) { return true; } } } else { // Check file type and call found() function if (type == WILDCARD_TYPE || type == file.GetType()) { if (found(file)) { return true; } } } } return false; }