void Client::initScreenshotDir() { if (!mOptions.screenshotDir.empty()) { mScreenshotDir = mOptions.screenshotDir; } else if (mScreenshotDir.empty()) { #ifdef _WIN32 mScreenshotDir = getSpecialFolderLocation(CSIDL_MYPICTURES); if (mScreenshotDir.empty()) mScreenshotDir = getSpecialFolderLocation(CSIDL_DESKTOP); #else mScreenshotDir = std::string(PHYSFS_getUserDir()) + "Desktop"; #endif if (config.getBoolValue("useScreenshotDirectorySuffix")) { std::string configScreenshotSuffix = config.getValue("screenshotDirectorySuffix", branding.getValue("appShort", "Mana")); if (!configScreenshotSuffix.empty()) { mScreenshotDir += "/" + configScreenshotSuffix; config.setValue("screenshotDirectorySuffix", configScreenshotSuffix); } } } }
// Reimplement so that we can use phys 2.0 on linux static char *my_pref_dir(const char *org, const char *app) { /* * We use XDG's base directory spec, even if you're not on Linux. * This isn't strictly correct, but the results are relatively sane * in any case. * * http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html */ const char *envr = getenv("XDG_DATA_HOME"); const char *append = "/"; char *retval = NULL; size_t len = 0; if (!envr) { /* You end up with "$HOME/.local/share/Game Name 2" */ envr = PHYSFS_getUserDir(); append = ".local/share/"; } /* if */ len = strlen(envr) + strlen(append) + strlen(app) + 2; retval = (char *) malloc(len); snprintf(retval, len, "%s%s%s/", envr, append, app); return retval; }
bool ResourceManager::setupWriteDir(const std::string& appWriteDirName) { std::string userDir = PHYSFS_getUserDir(); std::string dirName; #ifndef WIN32 dirName = stdext::format(".%s", appWriteDirName); #else dirName = appWriteDirName; #endif std::string writeDir = userDir + dirName; if(!PHYSFS_setWriteDir(writeDir.c_str())) { if(!PHYSFS_setWriteDir(userDir.c_str())) { g_logger.error("User directory not found."); return false; } if(!PHYSFS_mkdir(dirName.c_str())) { g_logger.error("Cannot create directory for saving configurations."); return false; } if(!PHYSFS_setWriteDir(writeDir.c_str())) { g_logger.error("Unable to set write directory."); return false; } } addToSearchPath(writeDir, true); //g_logger.debug(stdext::format("Setup write dir %s", writeDir)); return true; }
static void getPlatformUserDir(char * const tmpstr, size_t const size) { #if defined(WZ_OS_WIN) wchar_t tmpWStr[MAX_PATH]; if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, tmpWStr ) ) ) { if (WideCharToMultiByte(CP_UTF8, 0, tmpWStr, -1, tmpstr, size, NULL, NULL) == 0) { debug(LOG_ERROR, "Encoding conversion error."); exit(1); } strlcat(tmpstr, PHYSFS_getDirSeparator(), size); } else #elif defined(WZ_OS_MAC) FSRef fsref; OSErr error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &fsref); if (!error) error = FSRefMakePath(&fsref, (UInt8 *) tmpstr, size); if (!error) strlcat(tmpstr, PHYSFS_getDirSeparator(), size); else #endif if (PHYSFS_getUserDir()) { strlcpy(tmpstr, PHYSFS_getUserDir(), size); // Use PhysFS supplied UserDir (As fallback on Windows / Mac, default on Linux) } // If PhysicsFS fails (might happen if environment variable HOME is unset or wrong) then use the current working directory else if (getCurrentDir(tmpstr, size)) { strlcat(tmpstr, PHYSFS_getDirSeparator(), size); } else { debug(LOG_FATAL, "Can't get UserDir?"); abort(); } }
void setupPHYSFS() { std::string separator = PHYSFS_getDirSeparator(); // Game should be playable out of the source package on all // platforms PHYSFS_addToSearchPath("data", 1); PHYSFS_addToSearchPath("data/gfx.zip", 1); PHYSFS_addToSearchPath("data/sounds.zip", 1); PHYSFS_addToSearchPath("data/scripts.zip", 1); PHYSFS_addToSearchPath("data/backgrounds.zip", 1); #if defined(WIN32) // Just write in installation directory PHYSFS_setWriteDir("data"); #else // handle the case when it is installed PHYSFS_addToSearchPath(BLOBBY_INSTALL_PREFIX "/share/blobby", 1); PHYSFS_addToSearchPath(BLOBBY_INSTALL_PREFIX "/share/blobby/gfx.zip", 1); PHYSFS_addToSearchPath(BLOBBY_INSTALL_PREFIX "/share/blobby/sounds.zip", 1); PHYSFS_addToSearchPath(BLOBBY_INSTALL_PREFIX "/share/blobby/scripts.zip", 1); PHYSFS_addToSearchPath(BLOBBY_INSTALL_PREFIX "/share/blobby/backgrounds.zip", 1); // Create a search path in the home directory and ensure that // all paths exist and are actually directories std::string userdir = PHYSFS_getUserDir(); std::string userAppend = ".blobby"; std::string homedir = userdir + userAppend; PHYSFS_addToSearchPath(userdir.c_str(), 0); PHYSFS_setWriteDir(userdir.c_str()); probeDir(userAppend); probeDir(userAppend + separator + "replays"); probeDir(userAppend + separator + "gfx"); probeDir(userAppend + separator + "sounds"); probeDir(userAppend + separator + "scripts"); probeDir(userAppend + separator + "backgrounds"); PHYSFS_removeFromSearchPath(userdir.c_str()); PHYSFS_setWriteDir(homedir.c_str()); PHYSFS_addToSearchPath(homedir.c_str(), 0); #if defined(GAMEDATADIR) // A global installation path makes only sense on non-Windows // platforms std::string basedir = GAMEDATADIR; PHYSFS_addToSearchPath(basedir.c_str(), 1); PHYSFS_addToSearchPath((basedir + separator + "gfx.zip").c_str(), 1); PHYSFS_addToSearchPath((basedir + separator + "sounds.zip").c_str(), 1); PHYSFS_addToSearchPath((basedir + separator + "scripts.zip").c_str(), 1); PHYSFS_addToSearchPath((basedir + separator + "backgrounds.zip").c_str(), 1); #endif #endif }
static void open_history_file(void) { #if (defined PHYSFS_HAVE_READLINE) #if 0 const char *envr = getenv("TESTPHYSFS_HISTORY"); if (!envr) return; #else char envr[256]; strcpy(envr, PHYSFS_getUserDir()); strcat(envr, ".testphys_history"); #endif if (access(envr, F_OK) == 0) { char buf[512]; FILE *f = fopen(envr, "r"); if (!f) { printf("\n\n" "Could not open history file [%s] for reading!\n" " Will not have past history available.\n\n", envr); return; } /* if */ do { if (fgets(buf, sizeof (buf), f) == NULL) break; if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = '\0'; add_history(buf); } while (!feof(f)); fclose(f); } /* if */ history_file = fopen(envr, "ab"); if (!history_file) { printf("\n\n" "Could not open history file [%s] for appending!\n" " Will not be able to record this session's history.\n\n", envr); } /* if */ #endif } /* open_history_file */
void saveScreenshot() { static unsigned int screenshotCount = 0; SDL_Surface *screenshot = graphics->getScreenshot(); // Search for an unused screenshot name std::stringstream filenameSuffix; std::stringstream filename; std::fstream testExists; bool found = false; do { screenshotCount++; filename.str(""); filenameSuffix.str(""); filename << PHYSFS_getUserDir(); #if (defined __USE_UNIX98 || defined __FreeBSD__) filenameSuffix << ".aethyra/"; #elif defined __APPLE__ filenameSuffix << "Desktop/"; #endif filenameSuffix << "Ae_Screenshot_" << screenshotCount << ".png"; filename << filenameSuffix.str(); testExists.open(filename.str().c_str(), std::ios::in); found = !testExists.is_open(); testExists.close(); } while (!found); const bool success = ImageWriter::writePNG(screenshot, filename.str()); if (success) { if (chatWindow) chatWindow->chatLog(strprintf(_("Screenshot saved to %s"), filename.str().c_str()), BY_LOGGER); } else { if (chatWindow) chatWindow->chatLog(_("Saving screenshot failed!"), BY_LOGGER); logger->log("Error: could not save screenshot."); } SDL_FreeSurface(screenshot); }
// ---------------------------------------------------------------------------- void Editor::readConfigFile(IFileSystem* file_system) { IXMLReader* xml_reader = file_system->createXMLReader(path(PHYSFS_getBaseDir()) + "config.xml"); if (!xml_reader) { path dir = PHYSFS_getUserDir(); m_config_loc = dir + "/.stk-te"; xml_reader = file_system->createXMLReader(m_config_loc + "/config.xml"); if (!xml_reader) { PHYSFS_setWriteDir(dir.c_str()); PHYSFS_mkdir(".stk-te"); return; } } else m_config_loc = PHYSFS_getBaseDir(); const stringw node_name(L"data_dir"); const stringw res(L"res"); const stringw exe(L"exe"); while (xml_reader->read()) { if (xml_reader->getNodeType() == EXN_ELEMENT) { if (res.equals_ignore_case(xml_reader->getNodeName())) { m_screen_size = dimension2du( atol(((stringc)xml_reader->getAttributeValueSafe(L"x")).c_str()), atol(((stringc)xml_reader->getAttributeValueSafe(L"y")).c_str())); } else if (node_name.equals_ignore_case(xml_reader->getNodeName())) { m_data_loc = xml_reader->getAttributeValueSafe(L"path"); m_icons_loc = m_data_loc + "editor/icons/"; } else if (exe.equals_ignore_case(xml_reader->getNodeName())) { m_exe_loc = xml_reader->getAttributeValueSafe(L"path"); } } } xml_reader->drop(); } // readConfigFile
void Recorder::setRecordingFile(const std::string &msg) { std::string msgCopy = msg; trim(msgCopy); if (msgCopy.empty()) { if (mStream.is_open()) { mStream.close(); setVisible(false); /* * Message should go after mStream is closed so that it isn't * recorded. */ localChatTab->chatLog(_("Finishing recording."), BY_SERVER); } else { localChatTab->chatLog(_("Not currently recording."), BY_SERVER); } } else if (mStream.is_open()) { localChatTab->chatLog(_("Already recording."), BY_SERVER); } else { /* * Message should go before mStream is opened so that it isn't * recorded. */ localChatTab->chatLog(_("Starting to record..."), BY_SERVER); const std::string file = std::string(PHYSFS_getUserDir()) + "/.tmw/" + msgCopy; mStream.open(file.c_str(), std::ios_base::trunc); if (mStream.is_open()) setVisible(true); else localChatTab->chatLog(_("Failed to start recording."), BY_SERVER); } }
void init_lib_cache() { const char* user_dir; struct stat cache_info; printf("lib_cache.c:init_lib_cache() - Starting cache system:\n"); user_dir = PHYSFS_getUserDir(); snprintf(cache_path,sizeof(cache_path), "%s.lambda/cache",user_dir); printf("lib_cache.c:init_lib_cache() - cache path is %s\n",cache_path); if(stat(cache_path, &cache_info) != 0) { #ifdef __MINGW32__ mkdir((const char*)cache_path); #else mkdir((const char*)cache_path, 0700); #endif printf("lib_cache.c:init_lib_cache() - Created new cache directory\n"); } }
void vfs_init(char* argv) { int retval; struct stat st; const char* user_dir; char config_dir[PATH_MAX]; printf("vfs_init.c:vfs_init() - Init PhysFS..."); retval = PHYSFS_init(argv); if(retval==0) { printf("FAILED!\n"); printf("vfs_init.c:vfs_init() - PhysFS error: %s\n", PHYSFS_getLastError()); exit(EXIT_FAILURE); } printf("DONE!\n"); printf("vfs_init.c:vfs_init() - Refresh lambda config directory..."); user_dir = PHYSFS_getUserDir(); snprintf(config_dir,sizeof(config_dir),"%s.lambda",user_dir); if(stat(config_dir, &st) != 0) { #ifdef __MINGW32__ mkdir(config_dir); #else mkdir(config_dir, 0700); #endif } printf("DONE!\n"); printf("vfs_init.c:vfs_init() - Load core01.pak:\n"); retval = vfs_loadpak("data/core01.pak"); if(retval != 0) { printf("vfs_init.c:vfs_init() - Could not load core01.pak, this file is required!\n"); exit(EXIT_FAILURE); } printf("vfs_init.c:vfs_init() - Load core02.pak:\n"); retval = vfs_loadpak("data/core02.pak"); if(retval != 0) { printf("vfs_init.c:vfs_init() - Could not load core02.pak, this file is required!\n"); exit(EXIT_FAILURE); } }
void find_userdir() { std::string userdir; if (m_forced_userdir) { userdir = *m_forced_userdir; } else if (const char* env_userdir = getenv("SUPERTUX2_USER_DIR")) { userdir = env_userdir; } else { std::string physfs_userdir = PHYSFS_getUserDir(); #ifdef _WIN32 userdir = FileSystem::join(physfs_userdir, PACKAGE_NAME); #else userdir = FileSystem::join(physfs_userdir, "." PACKAGE_NAME); #endif } if (!FileSystem::is_directory(userdir)) { FileSystem::mkdir(userdir); log_info << "Created SuperTux userdir: " << userdir << std::endl; } if (!PHYSFS_setWriteDir(userdir.c_str())) { std::ostringstream msg; msg << "Failed to use userdir directory '" << userdir << "': " << PHYSFS_getLastError(); throw std::runtime_error(msg.str()); } PHYSFS_addToSearchPath(userdir.c_str(), 0); }
// Initialise PhysicsFS, set up basic search paths and add arguments from .ini file. // The .ini file can be in either the user directory or the same directory as the program. // The user directory is searched first. void PHYSFSX_init(int argc, char *argv[]) { #if defined(__unix__) const char *path = NULL; #endif #ifdef macintosh // Mac OS 9 char base_dir[PATH_MAX]; int bundle = 0; #else #define base_dir PHYSFS_getBaseDir() #endif PHYSFS_init(argv[0]); atexit(PHYSFSX_deinit); PHYSFS_permitSymbolicLinks(1); #ifdef macintosh strcpy(base_dir, PHYSFS_getBaseDir()); if (strstr(base_dir, ".app:Contents:MacOSClassic")) // the Mac OS 9 program is still in the .app bundle { char *p; bundle = 1; if (base_dir[strlen(base_dir) - 1] == ':') base_dir[strlen(base_dir) - 1] = '\0'; p = strrchr(base_dir, ':'); *p = '\0'; // path to 'Contents' p = strrchr(base_dir, ':'); *p = '\0'; // path to bundle p = strrchr(base_dir, ':'); *p = '\0'; // path to directory containing bundle } #endif #if (defined(__APPLE__) && defined(__MACH__)) // others? chdir(base_dir); // make sure relative hogdir paths work #endif #if defined(__unix__) char fullPath[PATH_MAX + 5]; # if !(defined(__APPLE__) && defined(__MACH__)) path = "~/.d2x-rebirth/"; # else path = "~/Library/Preferences/D2X Rebirth/"; # endif if (path[0] == '~') // yes, this tilde can be put before non-unix paths. { const char *home = PHYSFS_getUserDir(); strcpy(fullPath, home); // prepend home to the path path++; if (*path == *PHYSFS_getDirSeparator()) path++; strncat(fullPath, path, PATH_MAX + 5 - strlen(home)); } else strncpy(fullPath, path, PATH_MAX + 5); PHYSFS_setWriteDir(fullPath); if (!PHYSFS_getWriteDir()) { // need to make it char *p; char ancestor[PATH_MAX + 5]; // the directory which actually exists char child[PATH_MAX + 5]; // the directory relative to the above we're trying to make strcpy(ancestor, fullPath); while (!PHYSFS_getWriteDir() && ((p = strrchr(ancestor, *PHYSFS_getDirSeparator())))) { if (p[1] == 0) { // separator at the end (intended here, for safety) *p = 0; // kill this separator if (!((p = strrchr(ancestor, *PHYSFS_getDirSeparator())))) break; // give up, this is (usually) the root directory } p[1] = 0; // go to parent PHYSFS_setWriteDir(ancestor); } strcpy(child, fullPath + strlen(ancestor)); for (p = child; (p = strchr(p, *PHYSFS_getDirSeparator())); p++) *p = '/'; PHYSFS_mkdir(child); PHYSFS_setWriteDir(fullPath); } PHYSFS_addToSearchPath(PHYSFS_getWriteDir(), 1); #endif PHYSFS_addToSearchPath(base_dir, 1); InitArgs( argc,argv ); PHYSFS_removeFromSearchPath(base_dir); if (!PHYSFS_getWriteDir()) { PHYSFS_setWriteDir(base_dir); if (!PHYSFS_getWriteDir()) Error("can't set write dir: %s\n", PHYSFS_getLastError()); else PHYSFS_addToSearchPath(PHYSFS_getWriteDir(), 0); } //tell PHYSFS where hogdir is if (GameArg.SysHogDir) PHYSFS_addToSearchPath(GameArg.SysHogDir,1); #if defined(__unix__) else if (!GameArg.SysNoHogDir) PHYSFS_addToSearchPath(SHAREPATH, 1); #endif PHYSFSX_addRelToSearchPath("data", 1); // 'Data' subdirectory // For Macintosh, add the 'Resources' directory in the .app bundle to the searchpaths #if defined(__APPLE__) && defined(__MACH__) { ProcessSerialNumber psn = { 0, kCurrentProcess }; FSRef fsref; OSStatus err; err = GetProcessBundleLocation(&psn, &fsref); if (err == noErr) err = FSRefMakePath(&fsref, (ubyte *)fullPath, PATH_MAX); if (err == noErr) { strncat(fullPath, "/Contents/Resources/", PATH_MAX + 4 - strlen(fullPath)); fullPath[PATH_MAX + 4] = '\0'; PHYSFS_addToSearchPath(fullPath, 1); } } #elif defined(macintosh) if (bundle) { base_dir[strlen(base_dir)] = ':'; // go back in the bundle base_dir[strlen(base_dir)] = ':'; // go back in 'Contents' strncat(base_dir, ":Resources:", PATH_MAX - 1 - strlen(base_dir)); base_dir[PATH_MAX - 1] = '\0'; PHYSFS_addToSearchPath(base_dir, 1); } #endif }
ResourceManager::ResourceManager(const std::string &path) { mDefaultBody = 0; mDefaultFemale = 0; mDefaultHair = 0; mDefaultChest = 0; mDefaultLegs = 0; mDefaultFeet = 0; mBodyWidth = 0; mBodyHeight = 0; mNumParts = 5; // TODO: Calculate based on body.cfg std::string datapath = ""; std::string error; std::string dirName; // physfs code PHYSFS_init(path.c_str()); // add paths // writable first, since thats where updates will go to #if defined __unix__ mWriteDataPath = PHYSFS_getUserDir(); #elif defined __APPLE__ mWriteDataPath = PHYSFS_getUserDir(); mWriteDataPath.append("Library/Application Support/"); #elif defined _WIN32 TCHAR writePath[MAX_PATH+1]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, writePath); int length = _tcslen(writePath); mWriteDataPath.assign(&writePath[0], &writePath[length]); #endif #ifndef __unix__ dirName = "townslife"; #else dirName = ".townslife"; #endif PHYSFS_setWriteDir(mWriteDataPath.c_str()); if (!doesExist(dirName)) { if (PHYSFS_mkdir(dirName.c_str()) == 0) { error = PHYSFS_getLastError(); } } mWriteDataPath.append("/" + dirName); PHYSFS_setWriteDir(mWriteDataPath.c_str()); mWriteDataPath.append("/"); addPath(mWriteDataPath); // now add cfg and /data directory #if defined __unix__ datapath = PHYSFS_getBaseDir(); addPath(datapath); addPath(datapath + "data/"); #elif defined __APPLE__ CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char resPath[PATH_MAX]; CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)resPath, PATH_MAX); CFRelease(resourcesURL); addPath(resPath); #elif defined _WIN32 TCHAR exePath[MAX_PATH+1]; GetModuleFileName(0, exePath, MAX_PATH); length = _tcslen(exePath); datapath.append(&exePath[0], &exePath[length]); datapath = datapath.substr(0, datapath.find_last_of("\\") + 1); addPath(datapath); addPath(datapath + "data\\"); #endif }
void FS_Init(lua_State *L, char *argv[], char **pFilename) { #ifdef __MACOSX__ char *ch = NULL; const char *basedir; #endif FILE *fh; char magic[4] = "000"; /* array for the magic bytes used to recognize a zip archive */ char *dir = NULL; char *base = NULL; char appdata[4096]; // char **search_path = NULL; // char **copy; /* initialize PhysFS */ if (PHYSFS_init(argv[0]) ==0) { error(L, "Error: Could not initialize PhysFS: %s.", PHYSFS_getLastError()); } /* allow symlinks */ PHYSFS_permitSymbolicLinks(1); /* on Mac OS X applications are packed inside a folder with the ending .app; try to set the search path to this folder; if a file is not found in the base dir (the dir containing the app bundle) it is searched inside the bundle */ #ifdef __MACOSX__ ch = strstr(argv[0], "/Contents/MacOS"); if (ch != NULL) { /* substite the 'C' of 'Contents/MacOS' with a string terminator */ *(ch+1) = '\0'; if (*pFilename == NULL) { /* if no filename was selected */ chdir(argv[0]); } /* append app folder to search path */ if (PHYSFS_addToSearchPath(argv[0], 1) == 0) { error(L, "Error: Could not add application folder" "to search path: %s.", PHYSFS_getLastError()); } *(ch+1) = 'C'; } else { basedir = PHYSFS_getBaseDir(); if (*pFilename == NULL) { chdir(basedir); } if (PHYSFS_addToSearchPath(basedir, 1) == 0) { error(L, "Error: Could not add base dir to search path: %s.", PHYSFS_getLastError()); } } #else /* check whether we are on Linux or Unix */ #ifndef __WIN32__ /* on Linux or Unix: Try to append the share directory */ #ifdef SHARE_DIR PHYSFS_addToSearchPath(SHARE_DIR, 1); #endif #endif /* on every system but OS X, prepend base dir to search path */ if (PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 0) == 0) { error(L, "Error: Could not add base dir to search path: %s.", PHYSFS_getLastError()); } #endif /* * if a Lua file is given, try to mount the parent directory and change * the working directory * if an archive or directory is given, try to mount it */ if (*pFilename == NULL) { *pFilename = (char *)DEFAULT_FILE; if (PHYSFS_exists(*pFilename) == 0) { /* if default file not exists */ if (PHYSFS_exists(DEFAULT_ARCHIVE) != 0) { /* if default archive exists, prepend to search path */ if (PHYSFS_addToSearchPath(DEFAULT_ARCHIVE, 0) == 0) { error(L, "Error: Could not add default archive '" DEFAULT_ARCHIVE "' to search path: %s", PHYSFS_getLastError()); } } else { error(L, "Error: " "Neither the default Lua file '" DEFAULT_FILE "' nor the default archive '" DEFAULT_ARCHIVE "' could be found."); } } } else { /* try to change the working directory (only successful if directory is given) */ if (chdir(*pFilename) == 0) { /* prepend the new working directory to the search path */ if (PHYSFS_addToSearchPath(".", 0) == 0) { error(L, "Error: Could not add directory '%s' to search path: %s", argv[1], PHYSFS_getLastError()); } *pFilename = (char *)DEFAULT_FILE; } else { /* chdir was unsuccessful -> archive or Lua file was probably given on command line */ splitPath(*pFilename, &dir, &base); /* change the working directory to the directory with the archive or the Lua file */ chdir(dir); /* check if it's an archive; only zip is supported, so we check for the magic numbers */ fh = fopen(base, "r"); if (fh == NULL) { error(L, "Error: Could not open file '%s' for reading.", argv[1]); } fread(magic, 1, 4, fh); fclose(fh); /* look for the four signature bytes that every zip file has */ if (magic[0] == 0x50 && magic[1] == 0x4B && magic[2] == 0x03 && magic[3] == 0x04) { // fprintf(stdout, "Found zip archive: %s\n", base); if (PHYSFS_addToSearchPath(base, 0) == 0) { error(L, "Error: Could not add archive '%s' to search path: %s", argv[1], PHYSFS_getLastError()); } *pFilename = (char *)DEFAULT_FILE; } else { // fprintf(stdout, "Found Lua file: %s\n", base); /* prepend the new working directory to the search path */ if (PHYSFS_addToSearchPath(".", 0) == 0) { error(L, "Error: Could not add directory containing '%s' to search path: %s", base, PHYSFS_getLastError()); } /* change the filename to its basename -> later call to FS_runLuaFile will find it in the path */ *pFilename = base; } } } // char * xdgdatahome = getenv("XDG_DATA_HOME"); //if (!xdgdatahome) //{ strcpy(appdata, PHYSFS_getUserDir()); #ifdef __GNUC__ strcat(appdata, "/.local/share/"); #else strcat(appdata, "Application Data"); #endif //} //else // strcpy(appdata, xdgdatahome); // printf("%s", appdata); if(!PHYSFS_setWriteDir(appdata)) error(L, "Error: Could not set write directory '%s': %s", appdata, PHYSFS_getLastError()); strcat(appdata, "/Scriptum Plus/"); // strcat(appdata, appName); //char * relative_path = strcat("./Scriptum Plus/", appName); if(!PHYSFS_mkdir("/Scriptum Plus/")) error(L, "Error: Could not create write directory '%s': %s", appdata, PHYSFS_getLastError()); if(!PHYSFS_setWriteDir(appdata)) error(L, "Error: Could not set write directory '%s': %s", appdata, PHYSFS_getLastError()); PHYSFS_addToSearchPath(appdata, 0); atexit(FS_Quit); // search_path = PHYSFS_getSearchPath(); // copy = search_path; // while (*copy != NULL) { // printf("search path: %s\n", *copy++); // } // PHYSFS_freeList(search_path); }
string getUserDir() { return PHYSFS_getUserDir(); }
static int cmd_getuserdir(char *args) { (void)args; printf("User dir is [%s].\n", PHYSFS_getUserDir()); return(1); } /* cmd_getuserdir */
static void init_physfs(const char* argv0) { if(!PHYSFS_init(argv0)) { std::stringstream msg; msg << "Couldn't initialize physfs: " << PHYSFS_getLastError(); throw std::runtime_error(msg.str()); } // Initialize physfs (this is a slightly modified version of // PHYSFS_setSaneConfig const char* application = PACKAGE_NAME; const char* userdir = PHYSFS_getUserDir(); const char* dirsep = PHYSFS_getDirSeparator(); char* writedir = new char[strlen(userdir) + strlen(application) + 2]; // Set configuration directory sprintf(writedir, "%s.%s", userdir, application); if(!PHYSFS_setWriteDir(writedir)) { // try to create the directory char* mkdir = new char[strlen(application) + 2]; sprintf(mkdir, ".%s", application); if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) { std::ostringstream msg; msg << "Failed creating configuration directory '" << writedir << "': " << PHYSFS_getLastError(); delete[] writedir; delete[] mkdir; throw std::runtime_error(msg.str()); } delete[] mkdir; if(!PHYSFS_setWriteDir(writedir)) { std::ostringstream msg; msg << "Failed to use configuration directory '" << writedir << "': " << PHYSFS_getLastError(); delete[] writedir; throw std::runtime_error(msg.str()); } } PHYSFS_addToSearchPath(writedir, 0); delete[] writedir; // Search for archives and add them to the search path const char* archiveExt = "zip"; char** rc = PHYSFS_enumerateFiles("/"); size_t extlen = strlen(archiveExt); for(char** i = rc; *i != 0; ++i) { size_t l = strlen(*i); if((l > extlen) && ((*i)[l - extlen - 1] == '.')) { const char* ext = (*i) + (l - extlen); if(strcasecmp(ext, archiveExt) == 0) { const char* d = PHYSFS_getRealDir(*i); char* str = new char[strlen(d) + strlen(dirsep) + l + 1]; sprintf(str, "%s%s%s", d, dirsep, *i); PHYSFS_addToSearchPath(str, 1); delete[] str; } } } PHYSFS_freeList(rc); // when started from source dir... std::string dir = PHYSFS_getBaseDir(); dir += "/data"; std::string testfname = dir; testfname += "/credits.txt"; bool sourcedir = false; FILE* f = fopen(testfname.c_str(), "r"); if(f) { fclose(f); if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) { log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl; } else { sourcedir = true; } } #ifdef MACOSX // when started from Application file on Mac OS X... dir = PHYSFS_getBaseDir(); dir += "SuperTux.app/Contents/Resources/data"; testfname = dir + "/credits.txt"; sourcedir = false; f = fopen(testfname.c_str(), "r"); if(f) { fclose(f); if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) { msg_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl; } else { sourcedir = true; } } #endif if(!sourcedir) { #if defined(APPDATADIR) || defined(ENABLE_BINRELOC) std::string datadir; #ifdef ENABLE_BINRELOC char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME); datadir = brdatadir; free(brdatadir); #else datadir = APPDATADIR; #endif if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) { log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl; } #endif } // allow symbolic links PHYSFS_permitSymbolicLinks(1); //show search Path for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++) log_info << "[" << *i << "] is in the search path" << std::endl; }
int ReadConfigFile() { PHYSFS_file *infile; char *line, *token, *value, *ptr; // set defaults GameCfg.DigiVolume = 8; GameCfg.MusicVolume = 8; GameCfg.ReverseStereo = 0; GameCfg.OrigTrackOrder = 0; #if defined(__APPLE__) && defined(__MACH__) GameCfg.MusicType = MUSIC_TYPE_REDBOOK; #else GameCfg.MusicType = MUSIC_TYPE_BUILTIN; #endif GameCfg.CMLevelMusicPlayOrder = MUSIC_CM_PLAYORDER_CONT; GameCfg.CMLevelMusicTrack[0] = -1; GameCfg.CMLevelMusicTrack[1] = -1; memset(GameCfg.CMLevelMusicPath,0,PATH_MAX+1); memset(GameCfg.CMMiscMusic[SONG_TITLE],0,PATH_MAX+1); memset(GameCfg.CMMiscMusic[SONG_BRIEFING],0,PATH_MAX+1); memset(GameCfg.CMMiscMusic[SONG_ENDLEVEL],0,PATH_MAX+1); memset(GameCfg.CMMiscMusic[SONG_ENDGAME],0,PATH_MAX+1); memset(GameCfg.CMMiscMusic[SONG_CREDITS],0,PATH_MAX+1); #if defined(__APPLE__) && defined(__MACH__) GameCfg.OrigTrackOrder = 1; GameCfg.CMLevelMusicPlayOrder = MUSIC_CM_PLAYORDER_LEVEL; snprintf(GameCfg.CMLevelMusicPath, PATH_MAX, "%s", "descent.m3u"); snprintf(GameCfg.CMMiscMusic[SONG_TITLE], PATH_MAX, "%s%s", PHYSFS_getUserDir(), "Music/iTunes/iTunes Music/Insanity/Descent/02 Primitive Rage.mp3"); snprintf(GameCfg.CMMiscMusic[SONG_BRIEFING], PATH_MAX, "%s%s", PHYSFS_getUserDir(), "Music/iTunes/iTunes Music/Insanity/Descent/03 Outerlimits.mp3"); snprintf(GameCfg.CMMiscMusic[SONG_ENDLEVEL], PATH_MAX, "%s%s", PHYSFS_getUserDir(), "Music/iTunes/iTunes Music/Insanity/Descent/04 Close Call.mp3"); snprintf(GameCfg.CMMiscMusic[SONG_ENDGAME], PATH_MAX, "%s%s", PHYSFS_getUserDir(), "Music/iTunes/iTunes Music/Insanity/Descent/14 Insanity.mp3"); snprintf(GameCfg.CMMiscMusic[SONG_CREDITS], PATH_MAX, "%s%s", PHYSFS_getUserDir(), "Music/iTunes/iTunes Music/Insanity/Descent/05 The Darkness Of Space.mp3"); #endif GameCfg.GammaLevel = 0; memset(GameCfg.LastPlayer,0,CALLSIGN_LEN+1); memset(GameCfg.LastMission,0,MISSION_NAME_LEN+1); GameCfg.ResolutionX = 640; GameCfg.ResolutionY = 480; GameCfg.AspectX = 3; GameCfg.AspectY = 4; GameCfg.WindowMode = 0; GameCfg.TexFilt = 0; GameCfg.VSync = 0; GameCfg.Multisample = 0; GameCfg.FPSIndicator = 0; GameCfg.Grabinput = 1; infile = PHYSFSX_openReadBuffered("descent.cfg"); if (infile == NULL) { return 1; } while (!PHYSFS_eof(infile)) { int max_len = PHYSFS_fileLength(infile); // to be fully safe, assume the whole cfg consists of one big line MALLOC(line, char, max_len); memset(line, 0, max_len); PHYSFSX_gets(infile, line); ptr = &(line[0]); while (isspace(*ptr)) ptr++; if (*ptr != '\0') { token = strtok(ptr, "="); value = strtok(NULL, "="); if (!value) value = ""; if (!strcmp(token, DigiVolumeStr)) GameCfg.DigiVolume = strtol(value, NULL, 10); else if (!strcmp(token, MusicVolumeStr)) GameCfg.MusicVolume = strtol(value, NULL, 10); else if (!strcmp(token, ReverseStereoStr)) GameCfg.ReverseStereo = strtol(value, NULL, 10); else if (!strcmp(token, OrigTrackOrderStr)) GameCfg.OrigTrackOrder = strtol(value, NULL, 10); else if (!strcmp(token, MusicTypeStr)) GameCfg.MusicType = strtol(value, NULL, 10); else if (!strcmp(token, CMLevelMusicPlayOrderStr)) GameCfg.CMLevelMusicPlayOrder = strtol(value, NULL, 10); else if (!strcmp(token, CMLevelMusicTrack0Str)) GameCfg.CMLevelMusicTrack[0] = strtol(value, NULL, 10); else if (!strcmp(token, CMLevelMusicTrack1Str)) GameCfg.CMLevelMusicTrack[1] = strtol(value, NULL, 10); else if (!strcmp(token, CMLevelMusicPathStr)) { char * p; strncpy( GameCfg.CMLevelMusicPath, value, PATH_MAX ); p = strchr( GameCfg.CMLevelMusicPath, '\n'); if ( p ) *p = 0; } else if (!strcmp(token, CMMiscMusic0Str)) { char * p; strncpy( GameCfg.CMMiscMusic[SONG_TITLE], value, PATH_MAX ); p = strchr( GameCfg.CMMiscMusic[SONG_TITLE], '\n'); if ( p ) *p = 0; } else if (!strcmp(token, CMMiscMusic1Str)) { char * p; strncpy( GameCfg.CMMiscMusic[SONG_BRIEFING], value, PATH_MAX ); p = strchr( GameCfg.CMMiscMusic[SONG_BRIEFING], '\n'); if ( p ) *p = 0; } else if (!strcmp(token, CMMiscMusic2Str)) { char * p; strncpy( GameCfg.CMMiscMusic[SONG_ENDLEVEL], value, PATH_MAX ); p = strchr( GameCfg.CMMiscMusic[SONG_ENDLEVEL], '\n'); if ( p ) *p = 0; } else if (!strcmp(token, CMMiscMusic3Str)) { char * p; strncpy( GameCfg.CMMiscMusic[SONG_ENDGAME], value, PATH_MAX ); p = strchr( GameCfg.CMMiscMusic[SONG_ENDGAME], '\n'); if ( p ) *p = 0; } else if (!strcmp(token, CMMiscMusic4Str)) { char * p; strncpy( GameCfg.CMMiscMusic[SONG_CREDITS], value, PATH_MAX ); p = strchr( GameCfg.CMMiscMusic[SONG_CREDITS], '\n'); if ( p ) *p = 0; } else if (!strcmp(token, GammaLevelStr)) { GameCfg.GammaLevel = strtol(value, NULL, 10); gr_palette_set_gamma( GameCfg.GammaLevel ); } else if (!strcmp(token, LastPlayerStr)) { char * p; strncpy( GameCfg.LastPlayer, value, CALLSIGN_LEN ); p = strchr( GameCfg.LastPlayer, '\n'); if ( p ) *p = 0; } else if (!strcmp(token, LastMissionStr)) { char * p; strncpy( GameCfg.LastMission, value, MISSION_NAME_LEN ); p = strchr( GameCfg.LastMission, '\n'); if ( p ) *p = 0; } else if (!strcmp(token, ResolutionXStr)) GameCfg.ResolutionX = strtol(value, NULL, 10); else if (!strcmp(token, ResolutionYStr)) GameCfg.ResolutionY = strtol(value, NULL, 10); else if (!strcmp(token, AspectXStr)) GameCfg.AspectX = strtol(value, NULL, 10); else if (!strcmp(token, AspectYStr)) GameCfg.AspectY = strtol(value, NULL, 10); else if (!strcmp(token, WindowModeStr)) GameCfg.WindowMode = strtol(value, NULL, 10); else if (!strcmp(token, TexFiltStr)) GameCfg.TexFilt = strtol(value, NULL, 10); else if (!strcmp(token, VSyncStr)) GameCfg.VSync = strtol(value, NULL, 10); else if (!strcmp(token, MultisampleStr)) GameCfg.Multisample = strtol(value, NULL, 10); else if (!strcmp(token, FPSIndicatorStr)) GameCfg.FPSIndicator = strtol(value, NULL, 10); else if (!strcmp(token, GrabinputStr)) GameCfg.Grabinput = strtol(value, NULL, 10); } d_free(line); } PHYSFS_close(infile); if ( GameCfg.DigiVolume > 8 ) GameCfg.DigiVolume = 8; if ( GameCfg.MusicVolume > 8 ) GameCfg.MusicVolume = 8; if (GameCfg.ResolutionX >= 320 && GameCfg.ResolutionY >= 200) Game_screen_mode = SM(GameCfg.ResolutionX,GameCfg.ResolutionY); return 0; }
void initialize(const char* argv0, const char* , const char* application) { if(!PHYSFS_init(argv0)) throw Exception("failure while initialising physfs: %s", PHYSFS_getLastError()); const char* basedir = PHYSFS_getBaseDir(); const char* userdir = PHYSFS_getUserDir(); const char* dirsep = PHYSFS_getDirSeparator(); char* writedir = new char[strlen(userdir) + strlen(application) + 2]; sprintf(writedir, "%s.%s", userdir, application); if(!PHYSFS_setWriteDir(writedir)) { // try to create the directory... char* mkdir = new char[strlen(application)+2]; sprintf(mkdir, ".%s", application); if(!PHYSFS_setWriteDir(userdir) || ! PHYSFS_mkdir(mkdir)) { delete[] writedir; delete[] mkdir; throw Exception("failed creating configuration directory: '%s': %s", writedir, PHYSFS_getLastError()); } delete[] mkdir; if (!PHYSFS_setWriteDir(writedir)) { throw Exception("couldn't set configuration directory to '%s': %s", writedir, PHYSFS_getLastError()); } } PHYSFS_addToSearchPath(writedir, 0); PHYSFS_addToSearchPath(basedir, 1); delete[] writedir; /* Root out archives, and add them to search path... */ char* archiveExt = "zip"; if (archiveExt != NULL) { char **rc = PHYSFS_enumerateFiles("/"); char **i; size_t extlen = strlen(archiveExt); char *ext; for (i = rc; *i != NULL; i++) { size_t l = strlen(*i); if ((l > extlen) && ((*i)[l - extlen - 1] == '.')) { ext = (*i) + (l - extlen); if (strcasecmp(ext, archiveExt) == 0) { const char *d = PHYSFS_getRealDir(*i); char* str = new char[strlen(d) + strlen(dirsep) + l + 1]; sprintf(str, "%s%s%s", d, dirsep, *i); PHYSFS_addToSearchPath(str, 1); delete[] str; } /* if */ } /* if */ } /* for */ PHYSFS_freeList(rc); } /* if */ }
void find_userdir() const { std::string userdir; if (m_forced_userdir) { userdir = *m_forced_userdir; } else if (const char* env_userdir = getenv("SUPERTUX2_USER_DIR")) { userdir = env_userdir; } else { userdir = PHYSFS_getPrefDir("SuperTux","supertux2"); } //Kept for backwards-compatability only, hence the silence #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" std::string physfs_userdir = PHYSFS_getUserDir(); #pragma GCC diagnostic pop #ifdef _WIN32 std::string olduserdir = FileSystem::join(physfs_userdir, PACKAGE_NAME); #else std::string olduserdir = FileSystem::join(physfs_userdir, "." PACKAGE_NAME); #endif if (FileSystem::is_directory(olduserdir)) { boost::filesystem::path olduserpath(olduserdir); boost::filesystem::path userpath(userdir); boost::filesystem::directory_iterator end_itr; bool success = true; // cycle through the directory for (boost::filesystem::directory_iterator itr(olduserpath); itr != end_itr; ++itr) { try { boost::filesystem::rename(itr->path().string().c_str(), userpath / itr->path().filename()); } catch (const boost::filesystem::filesystem_error& err) { success = false; log_warning << "Failed to move contents of config directory: " << err.what() << std::endl; } } if (success) { try { boost::filesystem::remove_all(olduserpath); } catch (const boost::filesystem::filesystem_error& err) { success = false; log_warning << "Failed to remove old config directory: " << err.what(); } } if (success) { log_info << "Moved old config dir " << olduserdir << " to " << userdir << std::endl; } } if (!FileSystem::is_directory(userdir)) { FileSystem::mkdir(userdir); log_info << "Created SuperTux userdir: " << userdir << std::endl; } if (!PHYSFS_setWriteDir(userdir.c_str())) { std::ostringstream msg; msg << "Failed to use userdir directory '" << userdir << "': " << PHYSFS_getLastErrorCode(); throw std::runtime_error(msg.str()); } PHYSFS_mount(userdir.c_str(), NULL, 0); }
static void getPlatformUserDir(char * const tmpstr, size_t const size) { #if defined(WZ_OS_WIN) // When WZ_PORTABLE is passed, that means we want the config directory at the same location as the program file DWORD dwRet; wchar_t tmpWStr[MAX_PATH]; #ifndef WZ_PORTABLE if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, tmpWStr ) ) ) { #else if (dwRet = GetCurrentDirectoryW(MAX_PATH, tmpWStr)) { if(dwRet > MAX_PATH) { debug(LOG_FATAL, "Buffer exceeds maximum path to create directory. Exiting."); exit(1); } #endif if (WideCharToMultiByte(CP_UTF8, 0, tmpWStr, -1, tmpstr, size, NULL, NULL) == 0) { debug(LOG_FATAL, "Config directory encoding conversion error."); exit(1); } strlcat(tmpstr, PHYSFS_getDirSeparator(), size); } else #elif defined(WZ_OS_MAC) FSRef fsref; OSErr error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &fsref); if (!error) error = FSRefMakePath(&fsref, (UInt8 *) tmpstr, size); if (!error) strlcat(tmpstr, PHYSFS_getDirSeparator(), size); else #endif if (PHYSFS_getUserDir()) { strlcpy(tmpstr, PHYSFS_getUserDir(), size); // Use PhysFS supplied UserDir (As fallback on Windows / Mac, default on Linux) } // If PhysicsFS fails (might happen if environment variable HOME is unset or wrong) then use the current working directory else if (getCurrentDir(tmpstr, size)) { strlcat(tmpstr, PHYSFS_getDirSeparator(), size); } else { debug(LOG_FATAL, "Can't get UserDir?"); abort(); } } static void initialize_ConfigDir(void) { char tmpstr[PATH_MAX] = { '\0' }; if (strlen(configdir) == 0) { getPlatformUserDir(tmpstr, sizeof(tmpstr)); if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected. { debug(LOG_FATAL, "Error setting write directory to \"%s\": %s", tmpstr, PHYSFS_getLastError()); exit(1); } if (!PHYSFS_mkdir(WZ_WRITEDIR)) // s.a. { debug(LOG_FATAL, "Error creating directory \"%s\": %s", WZ_WRITEDIR, PHYSFS_getLastError()); exit(1); } // Append the Warzone subdir sstrcat(tmpstr, WZ_WRITEDIR); sstrcat(tmpstr, PHYSFS_getDirSeparator()); if (!PHYSFS_setWriteDir(tmpstr)) { debug( LOG_FATAL, "Error setting write directory to \"%s\": %s", tmpstr, PHYSFS_getLastError() ); exit(1); } } else { sstrcpy(tmpstr, configdir); // Make sure that we have a directory separator at the end of the string if (tmpstr[strlen(tmpstr) - 1] != PHYSFS_getDirSeparator()[0]) sstrcat(tmpstr, PHYSFS_getDirSeparator()); debug(LOG_WZ, "Using custom configuration directory: %s", tmpstr); if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected. { debug(LOG_FATAL, "Error setting write directory to \"%s\": %s", tmpstr, PHYSFS_getLastError()); exit(1); } // NOTE: This is currently only used for mingw builds for now. #if defined (WZ_CC_MINGW) if (!OverrideRPTDirectory(tmpstr)) { // since it failed, we just use our default path, and not the user supplied one. debug(LOG_ERROR, "Error setting exception hanlder to use directory %s", tmpstr); } #endif } // User's home dir first so we allways see what we write PHYSFS_addToSearchPath( PHYSFS_getWriteDir(), PHYSFS_PREPEND ); PHYSFS_permitSymbolicLinks(1); debug(LOG_WZ, "Write dir: %s", PHYSFS_getWriteDir()); debug(LOG_WZ, "Base dir: %s", PHYSFS_getBaseDir()); }
/** * Initializes the home directory. On UNIX and FreeBSD, ~/.mana is used. On * Windows and other systems we use the current working directory. */ void Client::initHomeDir() { mLocalDataDir = mOptions.localDataDir; if (mLocalDataDir.empty()) { #ifdef __APPLE__ // Use Application Directory instead of .mana mLocalDataDir = std::string(PHYSFS_getUserDir()) + "/Library/Application Support/" + branding.getValue("appName", "Mana"); #elif defined __HAIKU__ mLocalDataDir = std::string(PHYSFS_getUserDir()) + "/config/data/Mana"; #elif defined _WIN32 mLocalDataDir = getSpecialFolderLocation(CSIDL_LOCAL_APPDATA); if (mLocalDataDir.empty()) mLocalDataDir = std::string(PHYSFS_getUserDir()); mLocalDataDir += "/Mana"; #else mLocalDataDir = std::string(PHYSFS_getUserDir()) + "/.local/share/mana"; #endif } if (mkdir_r(mLocalDataDir.c_str())) { logger->error(strprintf(_("%s doesn't exist and can't be created! " "Exiting."), mLocalDataDir.c_str())); } mConfigDir = mOptions.configDir; if (mConfigDir.empty()) { const std::string app = branding.getValue("appShort", "manasource"); #ifdef __APPLE__ mConfigDir = mLocalDataDir + "/" + app; #elif defined __HAIKU__ mConfigDir = std::string(PHYSFS_getUserDir()) + "/config/settings/Mana" + branding.getValue("appName", "manasource"); #elif defined _WIN32 mConfigDir = getSpecialFolderLocation(CSIDL_APPDATA); if (mConfigDir.empty()) mConfigDir = mLocalDataDir; else mConfigDir += "/mana/" + app; #else mConfigDir = std::string(PHYSFS_getUserDir()) + "/.config/mana/" + app; #endif } if (mkdir_r(mConfigDir.c_str())) { logger->error(strprintf(_("%s doesn't exist and can't be created! " "Exiting."), mConfigDir.c_str())); } struct stat statbuf; std::string newConfigFile = mConfigDir + "/config.xml"; if (stat(newConfigFile.c_str(), &statbuf)) { std::string oldConfigFile = std::string(PHYSFS_getUserDir()) + "/.tmw/config.xml"; if (mRootDir.empty() && !stat(oldConfigFile.c_str(), &statbuf) && S_ISREG(statbuf.st_mode)) { std::ifstream oldConfig; std::ofstream newConfig; logger->log("Copying old TMW settings."); oldConfig.open(oldConfigFile.c_str(), std::ios::binary); newConfig.open(newConfigFile.c_str(), std::ios::binary); if (!oldConfig.is_open() || !newConfig.is_open()) logger->log("Unable to copy old settings."); else { newConfig << oldConfig.rdbuf(); newConfig.close(); oldConfig.close(); } } } }
void initPhysfs(const char* argv0) { if(!PHYSFS_init(argv0)) { std::stringstream msg; msg << "Couldn't initialize physfs: " << PHYSFS_getLastError(); throw std::runtime_error(msg.str()); } // Initialize physfs (this is a slightly modified version of // PHYSFS_setSaneConfig const char* application = /* PACKAGE_NAME */ "lincity"; const char* userdir = PHYSFS_getUserDir(); const char* dirsep = PHYSFS_getDirSeparator(); char* writedir = new char[strlen(userdir) + strlen(application) + 2]; // Set configuration directory sprintf(writedir, "%s.%s", userdir, application); if(!PHYSFS_setWriteDir(writedir)) { // try to create the directory char* mkdir = new char[strlen(application) + 2]; sprintf(mkdir, ".%s", application); if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) { std::ostringstream msg; msg << "Failed creating configuration directory '" << writedir << "': " << PHYSFS_getLastError(); delete[] writedir; delete[] mkdir; throw std::runtime_error(msg.str()); } delete[] mkdir; if(!PHYSFS_setWriteDir(writedir)) { std::ostringstream msg; msg << "Failed to use configuration directory '" << writedir << "': " << PHYSFS_getLastError(); delete[] writedir; throw std::runtime_error(msg.str()); } } PHYSFS_addToSearchPath(writedir, 0); delete[] writedir; // Search for archives and add them to the search path const char* archiveExt = "zip"; char** rc = PHYSFS_enumerateFiles("/"); size_t extlen = strlen(archiveExt); for(char** i = rc; *i != 0; ++i) { size_t l = strlen(*i); if((l > extlen) && ((*i)[l - extlen - 1] == '.')) { const char* ext = (*i) + (l - extlen); if(strcasecmp(ext, archiveExt) == 0) { const char* d = PHYSFS_getRealDir(*i); char* str = new char[strlen(d) + strlen(dirsep) + l + 1]; sprintf(str, "%s%s%s", d, dirsep, *i); PHYSFS_addToSearchPath(str, 1); delete[] str; } } } PHYSFS_freeList(rc); // when started from source dir... std::string dir = PHYSFS_getBaseDir(); dir += "/data"; std::string testfname = dir; testfname += "/images/tiles/images.xml"; FILE* f = fopen(testfname.c_str(), "r"); if(f) { fclose(f); if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) { #ifdef DEBUG std::cout << "Warning: Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n"; #endif } } #if defined(APPDATADIR) || defined(ENABLE_BINRELOC) std::string datadir; #ifdef ENABLE_BINRELOC BrInitError error; if (br_init (&error) == 0 && error != BR_INIT_ERROR_DISABLED) { printf ("Warning: BinReloc failed to initialize (error code %d)\n", error); printf ("Will fallback to hardcoded default path.\n"); } char* brdatadir = br_find_data_dir("/usr/local/share"); datadir = brdatadir; datadir += "/" PACKAGE_NAME; free(brdatadir); #else datadir = APPDATADIR; #endif if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) { std::cout << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n"; } #endif // allow symbolic links PHYSFS_permitSymbolicLinks(1); //show search Path for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++) printf("[%s] is in the search path.\n", *i); // ugly: set LINCITY_HOME environment variable const char* lincityhome = PHYSFS_getRealDir("colour.pal"); if(lincityhome == 0) { throw std::runtime_error("Couldn't locate lincity data (colour.pal)."); } std::cout << "LINCITY_HOME: " << lincityhome << "\n"; char tmp[256]; snprintf(tmp, sizeof(tmp), "LINCITY_HOME=%s", lincityhome); putenv(tmp); }
const char *ex_fsys_user_dir () { return PHYSFS_getUserDir(); }
const std::string& getUserDir() { // since this won't likely change during one execution, we cache the result static const std::string userDir = PHYSFS_getUserDir(); return userDir; }
const char *getUserDir() { return PHYSFS_getUserDir(); }
int mix_play_file(char *filename, int loop, void (*hook_finished_track)()) { SDL_RWops *rw = NULL; PHYSFS_file *filehandle = NULL; char full_path[PATH_MAX]; char *fptr; unsigned int bufsize = 0; mix_free_music(); // stop and free what we're already playing, if anything fptr = strrchr(filename, '.'); if (fptr == NULL) return 0; // It's a .hmp! if (!d_stricmp(fptr, ".hmp")) { hmp2mid(filename, ¤t_music_hndlbuf, &bufsize); rw = SDL_RWFromConstMem(current_music_hndlbuf,bufsize*sizeof(char)); current_music = Mix_LoadMUS_RW(rw); } // try loading music via given filename if (!current_music) current_music = Mix_LoadMUS(filename); // allow the shell convention tilde character to mean the user's home folder // chiefly used for default jukebox level song music referenced in 'descent.m3u' for Mac OS X if (!current_music && *filename == '~') { snprintf(full_path, PATH_MAX, "%s%s", PHYSFS_getUserDir(), &filename[1 + (!strncmp(&filename[1], PHYSFS_getDirSeparator(), strlen(PHYSFS_getDirSeparator())) ? strlen(PHYSFS_getDirSeparator()) : 0)]); current_music = Mix_LoadMUS(full_path); if (current_music) filename = full_path; // used later for possible error reporting } // no luck. so it might be in Searchpath. So try to build absolute path if (!current_music) { PHYSFSX_getRealPath(filename, full_path); current_music = Mix_LoadMUS(full_path); if (current_music) filename = full_path; // used later for possible error reporting } // still nothin'? Let's open via PhysFS in case it's located inside an archive if (!current_music) { filehandle = PHYSFS_openRead(filename); if (filehandle != NULL) { current_music_hndlbuf = d_realloc(current_music_hndlbuf, sizeof(char *)*PHYSFS_fileLength(filehandle)); bufsize = PHYSFS_read(filehandle, current_music_hndlbuf, sizeof(char), PHYSFS_fileLength(filehandle)); rw = SDL_RWFromConstMem(current_music_hndlbuf,bufsize*sizeof(char)); PHYSFS_close(filehandle); current_music = Mix_LoadMUS_RW(rw); } } if (current_music) { Mix_PlayMusic(current_music, (loop ? -1 : 1)); Mix_HookMusicFinished(hook_finished_track ? hook_finished_track : mix_free_music); return 1; } else { con_printf(CON_CRITICAL,"Music %s could not be loaded: %s\n", filename, Mix_GetError()); mix_stop_music(); } return 0; }
std::string FileSystem::getUserDir() { return PHYSFS_getUserDir(); }
bool Resources::Open(PString & argv0, PString & application) { if(!PHYSFS_init(argv0.GetPointer())) { PError << "failure while initialising physfs: " << PHYSFS_getLastError() << endl; return PFalse; } else { PTRACE(5, "successful initialize physfs"); } const char* basedir = PHYSFS_getBaseDir(); const char* userdir = PHYSFS_getUserDir(); const char* dirsep = PHYSFS_getDirSeparator(); char* writedir = new char[strlen(userdir) + application.GetLength() + 2]; sprintf(writedir, "%s.%s", userdir, application.GetPointer()); PTRACE(5, "physfs base directory: " << basedir); PTRACE(5, "physfs user directory: " << userdir); PTRACE(5, "physfs write directory: " << writedir); if(!PHYSFS_setWriteDir(writedir)) { // try to create the directory... char* mkdir = new char[application.GetLength()+2]; sprintf(mkdir, ".%s", application.GetPointer()); if(!PHYSFS_setWriteDir(userdir) || ! PHYSFS_mkdir(mkdir)) { delete[] writedir; delete[] mkdir; PError << "failed creating configuration directory: '" << writedir << "': " << PHYSFS_getLastError() << endl; return PFalse; } delete[] mkdir; if (!PHYSFS_setWriteDir(writedir)) { PError << "couldn't set configuration directory to '" << writedir << "': " << PHYSFS_getLastError() << endl; return PFalse; } } PHYSFS_addToSearchPath(writedir, 0); PHYSFS_addToSearchPath(basedir, 1); delete[] writedir; /* Root out archives, and add them to search path... */ if (resourceExt != NULL) { char **rc = PHYSFS_enumerateFiles("/"); char **i; size_t extlen = strlen(resourceExt); char *ext; for (i = rc; *i != NULL; i++) { size_t l = strlen(*i); if ((l > extlen) && ((*i)[l - extlen - 1] == '.')) { ext = (*i) + (l - extlen); if (strcasecmp(ext, resourceExt) == 0) { PTRACE(5, "Add resource '" << *i << "' to search path"); const char *d = PHYSFS_getRealDir(*i); char* str = new char[strlen(d) + strlen(dirsep) + l + 1]; sprintf(str, "%s%s%s", d, dirsep, *i); addToSearchPath(str, 1); delete[] str; }; }; }; PHYSFS_freeList(rc); } return PTrue; }