bool RageFileObjDirect::FinalFlush() { if( !(m_iMode & RageFile::WRITE) ) return true; /* Flush the output buffer. */ if( Flush() == -1 ) return false; /* Only do the rest of the flushes if SLOW_FLUSH is enabled. */ if( !(m_iMode & RageFile::SLOW_FLUSH) ) return true; /* Force a kernel buffer flush. */ if( fsync( m_iFD ) == -1 ) { WARN( ssprintf("Error synchronizing %s: %s", this->m_sPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); return false; } RString sError; if( !FlushDir(Dirname(m_sPath), sError) ) { WARN( ssprintf("Error synchronizing fsync(%s dir): %s", this->m_sPath.c_str(), sError.c_str()) ); SetError( sError ); return false; } return true; }
bool RageFileDriverDirect::Move( const CString &sOldPath_, const CString &sNewPath_ ) { CString sOldPath = sOldPath_; CString sNewPath = sNewPath_; FDB->ResolvePath( sOldPath ); FDB->ResolvePath( sNewPath ); if( this->GetFileType(sOldPath) == RageFileManager::TYPE_NONE ) return false; { const CString sDir = Dirname(sNewPath); CreateDirectories( m_sRoot + sDir ); } LOG->Trace( ssprintf("rename \"%s\" -> \"%s\"", (m_sRoot + sOldPath).c_str(), (m_sRoot + sNewPath).c_str()) ); if( DoRename(m_sRoot + sOldPath, m_sRoot + sNewPath) == -1 ) { LOG->Warn( ssprintf("rename(%s,%s) failed: %s", (m_sRoot + sOldPath).c_str(), (m_sRoot + sNewPath).c_str(), strerror(errno)) ); return false; } return true; }
bool RageFileDriverDirect::Move( const RString &sOldPath_, const RString &sNewPath_ ) { RString sOldPath = sOldPath_; RString sNewPath = sNewPath_; FDB->ResolvePath( sOldPath ); FDB->ResolvePath( sNewPath ); if( this->GetFileType(sOldPath) == RageFileManager::TYPE_NONE ) return false; { const RString sDir = Dirname(sNewPath); CreateDirectories( m_sRoot + sDir ); } int size = FDB->GetFileSize( sOldPath ); int hash = FDB->GetFileHash( sOldPath ); TRACE( ssprintf("rename \"%s\" -> \"%s\"", (m_sRoot + sOldPath).c_str(), (m_sRoot + sNewPath).c_str()) ); if( DoRename(m_sRoot + sOldPath, m_sRoot + sNewPath) == -1 ) { WARN( ssprintf("rename(%s,%s) failed: %s", (m_sRoot + sOldPath).c_str(), (m_sRoot + sNewPath).c_str(), strerror(errno)) ); return false; } FDB->DelFile( sOldPath ); FDB->AddFile( sNewPath, size, hash, NULL ); return true; }
RageFileBasic *RageFileDriverDirect::Open( const CString &sPath_, int iMode, int &iError ) { CString sPath = sPath_; ASSERT( sPath.size() && sPath[0] == '/' ); /* This partially resolves. For example, if "abc/def" exists, and we're opening * "ABC/DEF/GHI/jkl/mno", this will resolve it to "abc/def/GHI/jkl/mno"; we'll * create the missing parts below. */ FDB->ResolvePath( sPath ); if( iMode & RageFile::WRITE ) { const CString dir = Dirname(sPath); if( this->GetFileType(dir) != RageFileManager::TYPE_DIR ) CreateDirectories( m_sRoot + dir ); } RageFileObjDirect *ret = this->CreateInternal( m_sRoot + sPath ); if( ret->OpenInternal( m_sRoot + sPath, iMode, iError) ) return ret; SAFE_DELETE( ret ); return NULL; }
void AnimatedTexture::Load( const CString &sTexOrIniPath ) { ASSERT( vFrames.empty() ); // don't load more than once m_bSphereMapped = sTexOrIniPath.Find("sphere") != -1; if( sTexOrIniPath.Find("add") != -1 ) m_BlendMode = BLEND_ADD; else m_BlendMode = BLEND_NORMAL; if( GetExtension(sTexOrIniPath).CompareNoCase("ini")==0 ) { IniFile ini; if( !ini.ReadFile( sTexOrIniPath ) ) RageException::Throw( "Error reading %s: %s", sTexOrIniPath.c_str(), ini.GetError().c_str() ); if( !ini.GetKey("AnimatedTexture") ) RageException::Throw( "The animated texture file '%s' doesn't contain a section called 'AnimatedTexture'.", sTexOrIniPath.c_str() ); ini.GetValue( "AnimatedTexture", "TexVelocityX", m_fTexVelocityX ); ini.GetValue( "AnimatedTexture", "TexVelocityY", m_fTexVelocityY ); const CString sTexOrIniName = Dirname(sTexOrIniPath); RageTextureID ID; ID.bStretch = true; ID.bHotPinkColorKey = true; ID.bMipMaps = true; // use mipmaps in Models for( int i=0; i<1000; i++ ) { CString sFileName; float fDelay = 0; if( ini.GetValue( "AnimatedTexture", ssprintf("Frame%04d", i), sFileName ) && ini.GetValue( "AnimatedTexture", ssprintf("Delay%04d", i), fDelay ) ) { ID.filename = sTexOrIniName + sFileName; AnimatedTextureState state = { TEXTUREMAN->LoadTexture( ID ), fDelay }; vFrames.push_back( state ); } else break; } } else { RageTextureID ID; ID.filename = sTexOrIniPath; ID.bHotPinkColorKey = true; ID.bStretch = true; ID.bMipMaps = true; // use mipmaps in Models AnimatedTextureState state = { TEXTUREMAN->LoadTexture( ID ), 1 }; vFrames.push_back( state ); } }
static RString MakeTempFilename( const RString &sPath ) { /* "Foo/bar/baz" -> "Foo/bar/new.baz.new". Both prepend and append: we don't * want a wildcard search for the filename to match (foo.txt.new matches foo.txt*), * and we don't want to have the same extension (so "new.foo.sm" doesn't show up * in *.sm). */ return Dirname(sPath) + "new." + Basename(sPath) + ".new"; }
std::string FileUtils::GetExecutableDirectory() { wchar_t path[MAX_PATH]; path[MAX_PATH-1] = '\0'; GetModuleFileNameW(NULL, path, MAX_PATH - 1); std::string fullPath = UTILS_NS::WideToUTF8(path); return Dirname(fullPath); }
bool NotesWriterSM::Write(CString sPath, const Song &out, bool bSavingCache) { /* Flush dir cache when writing steps, so the old size isn't cached. */ FILEMAN->FlushDirCache( Dirname(sPath) ); unsigned i; int flags = RageFile::WRITE; /* If we're not saving cache, we're saving real data, so enable SLOW_FLUSH * to prevent data loss. If we're saving cache, this will slow things down * too much. */ if( !bSavingCache ) flags |= RageFile::SLOW_FLUSH; RageFile f; if( !f.Open( sPath, flags ) ) { LOG->Warn( "Error opening song file '%s' for writing: %s", sPath.c_str(), f.GetError().c_str() ); return false; } WriteGlobalTags( f, out ); if( bSavingCache ) { f.PutLine( ssprintf( "// cache tags:" ) ); f.PutLine( ssprintf( "#FIRSTBEAT:%.3f;", out.m_fFirstBeat ) ); f.PutLine( ssprintf( "#LASTBEAT:%.3f;", out.m_fLastBeat ) ); f.PutLine( ssprintf( "#SONGFILENAME:%s;", out.m_sSongFileName.c_str() ) ); f.PutLine( ssprintf( "#HASMUSIC:%i;", out.m_bHasMusic ) ); f.PutLine( ssprintf( "#HASBANNER:%i;", out.m_bHasBanner ) ); f.PutLine( ssprintf( "#MUSICLENGTH:%.3f;", out.m_fMusicLengthSeconds ) ); f.PutLine( ssprintf( "// end cache tags" ) ); } // // Save all Steps for this file // const vector<Steps*>& vpSteps = out.GetAllSteps(); for( i=0; i<vpSteps.size(); i++ ) { const Steps* pSteps = vpSteps[i]; if( pSteps->IsAutogen() ) continue; /* don't write autogen notes */ /* Only save steps that weren't loaded from a profile. */ if( pSteps->WasLoadedFromProfile() ) continue; WriteSMNotesTag( *pSteps, f, bSavingCache ); } return true; }
BOOL CBINDInstallDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon char filename[MAX_PATH]; char dirname[MAX_PATH]; char *fptr = &filename[0]; GetModuleFileName(NULL, filename, MAX_PATH); char *dptr = strrchr(filename,'\\'); int index = dptr - fptr; strncpy(dirname, filename, index); dirname[index] = '\0'; CString Dirname(dirname); m_currentDir = Dirname; CVersionInfo bindInst(filename); if(bindInst.IsValid()) m_version.Format(IDS_VERSION, bindInst.GetFileVersionString()); else m_version.LoadString(IDS_NO_VERSION); DWORD dwBufLen = MAX_PATH; char buf[MAX_PATH]; HKEY hKey; m_startOnInstall = CheckBINDService(); /* See if we are installed already */ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, BIND_SUBKEY, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { m_installed = TRUE; memset(buf, 0, MAX_PATH); // Get the install directory if (RegQueryValueEx(hKey, "InstallDir", NULL, NULL, (LPBYTE)buf, &dwBufLen) == ERROR_SUCCESS) if (strcmp(buf, "")) m_defaultDir = buf; RegCloseKey(hKey); } m_targetDir = m_defaultDir; // Set checkbox defaults m_autoStart = TRUE; m_keepFiles = TRUE; UpdateData(FALSE); return (TRUE); /* return(TRUE) unless you set the focus to a control */ }
void DirectFilenameDB::CacheFile( const RString &sPath ) { CHECKPOINT_M( root+sPath ); RString sDir = Dirname( sPath ); FileSet *pFileSet = GetFileSet( sDir, false ); if( pFileSet == NULL ) { // This directory isn't cached so do nothing. m_Mutex.Unlock(); // Locked by GetFileSet() return; } while( !pFileSet->m_bFilled ) m_Mutex.Wait(); #if defined(WIN32) // There is almost surely a better way to do this WIN32_FIND_DATA fd; HANDLE hFind = DoFindFirstFile( root+sPath, &fd ); if( hFind == INVALID_HANDLE_VALUE ) { m_Mutex.Unlock(); // Locked by GetFileSet() return; } File f( fd.cFileName ); f.dir = !!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); f.size = fd.nFileSizeLow; f.hash = fd.ftLastWriteTime.dwLowDateTime; pFileSet->files.insert( f ); FindClose( hFind ); #else File f( Basename(sPath) ); struct stat st; if( DoStat(root+sPath, &st) == -1 ) { int iError = errno; /* If it's a broken symlink, ignore it. Otherwise, warn. */ /* Huh? */ WARN( ssprintf("File '%s' is gone! (%s)", sPath.c_str(), strerror(iError)) ); } else { f.dir = (st.st_mode & S_IFDIR); f.size = (int)st.st_size; f.hash = st.st_mtime; } pFileSet->files.insert(f); #endif m_Mutex.Unlock(); // Locked by GetFileSet() }
/* ------------------------------------------------------- * make_dir: * must understand perfectly!!! * * Takes a pathname as parameter * * (1) set the device * (2) get parent MINODE by using dirname with * getino * Load MINODE using iget * (3) call my_mkdir(MINODE* parent, char* name) * --------------------------------------------------------*/ void make_dir(char* path) { MINODE* pip; // parent MINODE* int dev, pino; // device, parent ino // parent = path to parent directory, child = basename char* parent, *child; // (1) Set device according to relative or absolute path if(path[0] == '/') dev = root->dev; else dev = running->cwd->dev; // (2) Separate path into dirname and basename parent = strdup(Dirname(path)); // make copies child = strdup(Basename(path)); // Debug print //printf("parent: %s\n", parent); //printf("child: %s\n", child); // (3) get in memory MINODE of parent directory pino = getino(&dev, parent); // First, get parent ino pip = iget(dev, pino); // Then use it to load INODE into minode[] table // (4) Error checking on found MINODE if(pip == NULL) // (4.1) ensure the MINODE was found { printf("Error: unable to locate %s\n", parent); } else if(!isdir(pip)) // (4.2) is DIR { printf("Error: %s is not a directory\n", parent); } else if(search(pip, child) != 0) // (4.3) child does not already exist { // the child was already found printf("Error: %s already exists in %s\n", child, parent); } // (5) We've verified that parent path exists, is a directory // and child does not exist in it, so add to it else my_mkdir(pip,child); // No matter what, dont forget to write back! // Release parent from minode[] table and write back to disk iput(pip); }
void ScreenGameplaySyncMachine::Init() { m_bForceNoNetwork = true; GAMESTATE->m_PlayMode.Set( PLAY_MODE_REGULAR ); GAMESTATE->SetCurrentStyle( GAMEMAN->GetHowToPlayStyleForGame(GAMESTATE->m_pCurGame) ); AdjustSync::ResetOriginalSyncData(); RString sFile = THEME->GetPathO("ScreenGameplaySyncMachine","music"); // Allow themers to use either a .ssc or .sm file for this. -aj SSCLoader loaderSSC; SMLoader loaderSM; if(sFile.Right(4) == ".ssc") loaderSSC.LoadFromSimfile( sFile, m_Song ); else loaderSM.LoadFromSimfile( sFile, m_Song ); m_Song.SetSongDir( Dirname(sFile) ); m_Song.TidyUpData(); GAMESTATE->m_pCurSong.Set( &m_Song ); // Needs proper StepsType -freem vector<Steps*> vpSteps; SongUtil::GetPlayableSteps( &m_Song, vpSteps ); ASSERT_M(vpSteps.size() > 0, "No playable steps for ScreenGameplaySyncMachine"); Steps *pSteps = vpSteps[0]; GAMESTATE->m_pCurSteps[GAMESTATE->GetFirstHumanPlayer()].Set( pSteps ); GamePreferences::m_AutoPlay.Set( PC_HUMAN ); ScreenGameplayNormal::Init(); SO_GROUP_ASSIGN( GAMESTATE->m_SongOptions, ModsLevel_Stage, m_AutosyncType, SongOptions::AUTOSYNC_MACHINE ); ClearMessageQueue(); // remove all of the messages set in ScreenGameplay that animate "ready", "here we go", etc. GAMESTATE->m_bGameplayLeadIn.Set( false ); m_DancingState = STATE_DANCING; m_textSyncInfo.SetName( "SyncInfo" ); m_textSyncInfo.LoadFromFont( THEME->GetPathF(m_sName,"SyncInfo") ); ActorUtil::LoadAllCommands( m_textSyncInfo, m_sName ); this->AddChild( &m_textSyncInfo ); this->SubscribeToMessage( Message_AutosyncChanged ); RefreshText(); }
// Sprite file has the format: // // [Sprite] // Texture=Textures\Logo.bmp // Frame0000=0 // Delay0000=1.0 // Frame0001=3 // Delay0000=2.0 // BaseRotationXDegrees=0 // BaseRotationYDegrees=0 // BaseRotationZDegrees=0 // BaseZoomX=1 // BaseZoomY=1 // BaseZoomZ=1 bool Sprite::LoadFromSpriteFile( RageTextureID ID ) { LOG->Trace( ssprintf("Sprite::LoadFromSpriteFile(%s)", ID.filename.c_str()) ); //Init(); m_sSpritePath = ID.filename; // read sprite file IniFile ini; if( !ini.ReadFile( m_sSpritePath ) ) RageException::Throw( "Error opening Sprite file '%s'.", m_sSpritePath.c_str() ); LoadFromNode( Dirname(m_sSpritePath), ini.GetChild("Sprite") ); return true; }
bool CreateDirectory(const std::string& dir, bool recursive) { if (IsDirectory(dir)) { return true; } string parent(Dirname(dir)); if (recursive && parent.size() > 0 && !IsDirectory(parent)) { if (!CreateDirectory(parent, true)) return false; } return CreateDirectoryImpl(dir); }
/* --------------------------------------------------------------- * creat_r: * Given path of a file to be made, * get the parent's MINODE and ensure that it is a DIR * and that the new file does not already exist in it -------------------------------------------------------------------*/ void creat_r(char* path) { MINODE* pip; char* parent, *child; int dev, pino; // (1) Set device according to relative or absolute pathname if(path[0] == '/') dev = root->dev; else dev = running->cwd->dev; parent = strdup(Dirname(path)); child = strdup(Basename(path)); // (3) get in memory MINODE of parent directory // First, get parent ino pino = getino(&dev, parent); // Then use it to load MINODE into minode[] table pip = iget(dev, pino); // (4)Verify pip // (4.1) was found if(pip == NULL) { printf("Error: unable to locate %s\n", parent); } // (4.2) is directory else if(!isdir(pip)) { printf("Error: %s is not a directory\n", parent); } // (4.3) does not already contain child else if(search(pip, child) != 0) // the child was already found { printf("Error: %s already exists in %s\n", child, parent); } // (5) We've verified that parent path exists, is a directory // and child does not exist in it, so add to it else my_creat(pip,child); iput(pip); }
bool RageFileObjDirect::FinalFlush() { if( !(m_iMode & RageFile::WRITE) ) return true; /* Flush the output buffer. */ if( Flush() == -1 ) return false; /* Only do the rest of the flushes if SLOW_FLUSH is enabled. */ if( !(m_iMode & RageFile::SLOW_FLUSH) ) return true; /* Force a kernel buffer flush. */ if( fsync( m_iFD ) == -1 ) { WARN( ssprintf("Error synchronizing %s: %s", this->m_sPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); return false; } #if !defined(WIN32) /* Wait for the directory to be flushed. */ int dirfd = open( Dirname(m_sPath), O_RDONLY ); if( dirfd == -1 ) { WARN( ssprintf("Error synchronizing open(%s dir): %s", this->m_sPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); return false; } if( fsync( dirfd ) == -1 ) { WARN( ssprintf("Error synchronizing fsync(%s dir): %s", this->m_sPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); close( dirfd ); return false; } close( dirfd ); #endif return true; }
void Transition::Load( CString sBGAniDir ) { if( IsADirectory(sBGAniDir) && sBGAniDir.Right(1) != "/" ) sBGAniDir += "/"; this->RemoveAllChildren(); m_sprTransition.Load( sBGAniDir ); m_sprTransition->PlayCommand( "On" ); this->AddChild( m_sprTransition ); m_fLengthSeconds = m_sprTransition->GetTweenTimeLeft(); m_State = waiting; // load sound from file specified by ini, or use the first sound in the directory if( IsADirectory(sBGAniDir) ) { IniFile ini; ini.ReadFile( sBGAniDir+"/BGAnimation.ini" ); CString sSoundFileName; if( ini.GetValue("BGAnimation","Sound", sSoundFileName) ) { FixSlashesInPlace( sSoundFileName ); CString sPath = sBGAniDir+sSoundFileName; CollapsePath( sPath ); m_sound.Load( sPath ); } else { m_sound.Load( sBGAniDir ); } } else if( GetExtension(sBGAniDir).CompareNoCase("xml") == 0 ) { CString sSoundFile; XNode xml; xml.LoadFromFile( sBGAniDir ); if( xml.GetAttrValue( "Sound", sSoundFile ) ) m_sound.Load( Dirname(sBGAniDir) + sSoundFile ); } }
void XmlFileUtil::AnnotateXNodeTree( XNode *pNode, const RString &sFile ) { RString sDir = Dirname( sFile ); vector<XNode *> queue; queue.push_back( pNode ); while( !queue.empty() ) { pNode = queue.back(); queue.pop_back(); FOREACH_Child( pNode, pChild ) queue.push_back( pChild ); /* Source file, for error messages: */ pNode->AppendAttr( "_Source", sFile ); /* Directory of caller, for relative paths: */ pNode->AppendAttr( "_Dir", sDir ); /* Note that this node came from a legacy XML file */ pNode->AppendAttr( "_LegacyXml", true ); } }
void FileTransfer::StartTransfer( TransferType type, const RString &sURL, const RString &sSrcFile, const RString &sDestFile ) { RString Proto; RString Server; int Port=80; RString sAddress; if( !ParseHTTPAddress( sURL, Proto, Server, Port, sAddress ) ) { m_sStatus = "Invalid URL."; m_bFinished = true; UpdateProgress(); return; } m_bSavingFile = sDestFile != ""; m_sBaseAddress = "http://" + Server; if( Port != 80 ) m_sBaseAddress += ssprintf( ":%d", Port ); m_sBaseAddress += "/"; if( sAddress.Right(1) != "/" ) { m_sEndName = Basename( sAddress ); m_sBaseAddress += Dirname( sAddress ); } else { m_sEndName = ""; } // Open the file... // First find out if a file by this name already exists if so, then we gotta // ditch out. // XXX: This should be fixed by a prompt or something? // if we are not talking about a file, let's not worry if( m_sEndName != "" && m_bSavingFile ) { if( !m_fOutputFile.Open( sDestFile, RageFile::WRITE | RageFile::STREAMED ) ) { m_sStatus = m_fOutputFile.GetError(); UpdateProgress(); return; } } // Continue... sAddress = URLEncode( sAddress ); if ( sAddress != "/" ) sAddress = "/" + sAddress; m_wSocket.close(); m_wSocket.create(); m_wSocket.blocking = true; if( !m_wSocket.connect( Server, (short) Port ) ) { m_sStatus = "Failed to connect."; UpdateProgress(); return; } // Produce HTTP header RString sAction; switch( type ) { case upload: sAction = "POST"; break; case download: sAction = "GET"; break; } vector<RString> vsHeaders; vsHeaders.push_back( sAction+" "+sAddress+" HTTP/1.0" ); vsHeaders.push_back( "Host: " + Server ); vsHeaders.push_back( "Cookie: " + g_sCookie.Get() ); vsHeaders.push_back( "Connection: closed" ); string sBoundary = "--ZzAaB03x"; vsHeaders.push_back( "Content-Type: multipart/form-data; boundary=" + sBoundary ); RString sRequestPayload; if( type == upload ) { RageFile f; if( !f.Open( sSrcFile ) ) FAIL_M( f.GetError() ); sRequestPayload.reserve( f.GetFileSize() ); int iBytesRead = f.Read( sRequestPayload ); if( iBytesRead == -1 ) FAIL_M( f.GetError() ); sRequestPayload = "--" + sBoundary + "\r\n" + "Content-Disposition: form-data; name=\"name\"\r\n" + "\r\n" + "Chris\r\n" + "--" + sBoundary + "\r\n" + "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + Basename(sSrcFile) + "\"\r\n" + "Content-Type: application/zip\r\n" + "\r\n" + sRequestPayload + "\r\n" + "--" + sBoundary + "--"; } /* if( sRequestPayload.size() > 0 ) { sHeader += "Content-Type: application/octet-stream\r\n"; sHeader += "Content-Length: multipart/form-data; boundary=" + sBoundary + "\r\n"; //sHeader += "Content-Length: " + ssprintf("%d",sRequestPayload.size()) + "\r\n"; } */ vsHeaders.push_back( "Content-Length: " + ssprintf("%zd",sRequestPayload.size()) ); RString sHeader; FOREACH_CONST( RString, vsHeaders, h ) sHeader += *h + "\r\n"; sHeader += "\r\n"; m_wSocket.SendData( sHeader.c_str(), sHeader.length() ); m_wSocket.SendData( "\r\n" ); m_wSocket.SendData( sRequestPayload.GetBuffer(), sRequestPayload.size() ); m_sStatus = "Header Sent."; m_wSocket.blocking = false; m_bIsDownloading = true; m_sBUFFER = ""; m_bGotHeader = false; UpdateProgress(); }
void ScreenPackages::EnterURL( const CString & sURL ) { CString Proto; CString Server; int Port=80; CString sAddress; if( !ParseHTTPAddress( sURL, Proto, Server, Port, sAddress ) ) { m_sStatus = "Invalid URL."; UpdateProgress(); return; } //Determine if this is a website, or a package? //Criteria: does it end with *zip? if( sAddress.Right(3).CompareNoCase("zip") == 0 ) m_bIsPackage=true; else m_bIsPackage = false; m_sBaseAddress = "http://" + Server; if( Port != 80 ) m_sBaseAddress += ssprintf( ":%d", Port ); m_sBaseAddress += "/"; if( sAddress.Right(1) != "/" ) { m_sEndName = Basename( sAddress ); m_sBaseAddress += Dirname( sAddress ); } else { m_sEndName = ""; } //Open the file... //First find out if a file by this name already exists //if so, then we gotta ditch out. //XXX: This should be fixed by a prompt or something? //if we are not talking about a file, let's not worry if( m_sEndName != "" && m_bIsPackage ) { CStringArray AddTo; GetDirListing( "Packages/"+m_sEndName, AddTo, false, false ); if ( AddTo.size() > 0 ) { m_sStatus = "File Already Exists"; UpdateProgress(); return; } if( !m_fOutputFile.Open( "Packages/"+m_sEndName, RageFile::WRITE | RageFile::STREAMED ) ) { m_sStatus = m_fOutputFile.GetError(); UpdateProgress(); return; } } //Continue... sAddress = URLEncode( sAddress ); if ( sAddress != "/" ) sAddress = "/" + sAddress; m_wSocket.close(); m_wSocket.create(); m_wSocket.blocking = true; if( !m_wSocket.connect( Server, (short) Port ) ) { m_sStatus = "Failed to connect."; UpdateProgress(); return; } //Produce HTTP header CString Header=""; Header = "GET "+sAddress+" HTTP/1.0\r\n"; Header+= "Host: " + Server + "\r\n"; Header+= "Connection: closed\r\n\r\n"; m_wSocket.SendData( Header.c_str(), Header.length() ); m_sStatus = "Header Sent."; m_wSocket.blocking = false; m_bIsDownloading = true; m_sBUFFER = ""; m_bGotHeader = false; UpdateProgress(); return; }
RageFileObjDirect::~RageFileObjDirect() { bool bFailed = !FinalFlush(); if( m_iFD != -1 ) { if( close( m_iFD ) == -1 ) { WARN( ssprintf("Error closing %s: %s", this->m_sPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); bFailed = true; } } if( !(m_iMode & RageFile::WRITE) || (m_iMode & RageFile::STREAMED) ) return; /* We now have path written to MakeTempFilename(m_sPath). * Rename the temporary file over the real path. */ do { if( bFailed || WriteFailed() ) break; /* We now have path written to MakeTempFilename(m_sPath). Rename the * temporary file over the real path. This should be an atomic operation * with a journalling filesystem. That is, there should be no * intermediate state a JFS might restore the file we're writing (in the * case of a crash/powerdown) to an empty or partial file. */ RString sOldPath = MakeTempFilename(m_sPath); RString sNewPath = m_sPath; #if defined(WIN32) if( WinMoveFile(DoPathReplace(sOldPath), DoPathReplace(sNewPath)) ) return; /* We failed. */ int err = GetLastError(); const RString error = werr_ssprintf( err, "Error renaming \"%s\" to \"%s\"", sOldPath.c_str(), sNewPath.c_str() ); WARN( ssprintf("%s", error.c_str()) ); SetError( error ); break; #else if( rename( sOldPath, sNewPath ) == -1 ) { WARN( ssprintf("Error renaming \"%s\" to \"%s\": %s", sOldPath.c_str(), sNewPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); break; } if( m_iMode & RageFile::SLOW_FLUSH ) { RString sError; if( !FlushDir(Dirname(m_sPath), sError) ) { WARN( ssprintf("Error synchronizing fsync(%s dir): %s", this->m_sPath.c_str(), sError.c_str()) ); SetError( sError ); } } // Success. return; #endif } while(0); // The write or the rename failed. Delete the incomplete temporary file. DoRemove( MakeTempFilename(m_sPath) ); }
Actor *ActorUtil::LoadFromNode( const XNode* _pNode, Actor *pParentActor ) { ASSERT( _pNode != NULL ); XNode node = *_pNode; // Remove this in favor of using conditionals in Lua. -Chris // There are a number of themes out there that depend on this (including // sm-ssc default). Probably for the best to leave this in. -aj { bool bCond; if( node.GetAttrValue("Condition", bCond) && !bCond ) return NULL; } RString sClass; bool bHasClass = node.GetAttrValue( "Class", sClass ); if( !bHasClass ) bHasClass = node.GetAttrValue( "Type", sClass ); bool bLegacy = (node.GetAttr( "_LegacyXml" ) != NULL); if( !bHasClass && bLegacy ) sClass = GetLegacyActorClass( &node ); map<RString,CreateActorFn>::iterator iter = g_pmapRegistrees->find( sClass ); if( iter == g_pmapRegistrees->end() ) { RString sFile; if (bLegacy && node.GetAttrValue("File", sFile) && sFile != "") { RString sPath; // Handle absolute paths correctly if (sFile.Left(1) == "/") sPath = sFile; else sPath = Dirname(GetSourcePath(&node)) + sFile; if (ResolvePath(sPath, GetWhere(&node))) { Actor *pNewActor = MakeActor(sPath, pParentActor); if (pNewActor == NULL) return NULL; if (pParentActor) pNewActor->SetParent(pParentActor); pNewActor->LoadFromNode(&node); return pNewActor; } } // sClass is invalid RString sError = ssprintf( "%s: invalid Class \"%s\"", ActorUtil::GetWhere(&node).c_str(), sClass.c_str() ); LuaHelpers::ReportScriptError(sError); return new Actor; // Return a dummy object so that we don't crash in AutoActor later. } const CreateActorFn &pfn = iter->second; Actor *pRet = pfn(); if( pParentActor ) pRet->SetParent( pParentActor ); pRet->LoadFromNode( &node ); return pRet; }
/* --------------------------------------------------------------- * rm_dir: * (1) ask for pathname to rmdir * (2) get rmdir's ino * ino = getino(&dev, pathname) * (3) get a pointer to its MINODE[] * mip = iget(dev, ino) * (4) check DIR type && not busy && is empty * (5) get parent directory into memory -----------------------------------------------------------------*/ void rm_dir(char* path) { // (1) Asks for pathname MINODE* mip; // directory to remove MINODE* pip; // parent minode int i; int ino, pino; // inumber and parent inumber int dev = running->cwd->dev; // (2) get inumber if((ino = getino(&dev, path)) == 0) { printf("Could not find directory %s\n", path); return; } // get pointer to MINODE[] of file to Dir to remove mip = iget(dev, ino); if(mip == NULL) { printf("Error: Unable to find directory %s\n", path); return; } // (3) Check DIR, not BUSY, and is empty if(!isdir(mip)) { printf("Error: %s is not a directory\n", path); iput(mip); return; } // (3.1) not BUSY if(mip->refCount > 1 || mip->mounted || mip == running->cwd) { printf("Error: %s is in use\n", path); iput(mip); return; } if(!isempty(mip)) // (3.2) is empty { printf("Error: %s is not empty\n", path); iput(mip); return; } char* parentPath = strdup(Dirname(path)); printf("parent path = %s\n", parentPath); char* base = strdup(Basename(path)); printf("base (to remove) = %s\n", base); // (5) get parent directory into memory pino = getino(&dev, parentPath); // get parent ino pip = iget(dev, pino); // get parent MINODE* rm_child(pip, base); // (6) Passed all the checks, deallocate block and inode // (6.1) deallocate block for(i=0; i<12; i++) { if(mip->INODE.i_block[i] == 0) // block already 0 continue; // Deallocate the block bdealloc(mip->dev, mip->INODE.i_block[i]); } // (6.2) Deallocate the INODE and inumber idealloc(mip->dev, mip->ino); mip->refCount=0; // Free minode[] entry pip->INODE.i_links_count--; pip->dirty = 1; iput(pip); }
bool msAnimation::LoadMilkshapeAsciiBones( CString sAniName, CString sPath ) { FixSlashesInPlace(sPath); const CString sDir = Dirname( sPath ); RageFile f; if ( !f.Open(sPath) ) RageException::Throw( "Model:: Could not open \"%s\": %s", sPath.c_str(), f.GetError().c_str() ); CString sLine; int iLineNum = 0; msAnimation &Animation = *this; bool bLoaded = false; while( f.GetLine( sLine ) > 0 ) { iLineNum++; if (!strncmp (sLine, "//", 2)) continue; // // bones // int nNumBones = 0; if( sscanf (sLine, "Bones: %d", &nNumBones) != 1 ) continue; char szName[MS_MAX_NAME]; Animation.Bones.resize( nNumBones ); for( int i = 0; i < nNumBones; i++ ) { msBone& Bone = Animation.Bones[i]; // name if( f.GetLine( sLine ) <= 0 ) THROW; if (sscanf (sLine, "\"%[^\"]\"", szName) != 1) THROW; strcpy( Bone.szName, szName ); // parent if( f.GetLine( sLine ) <= 0 ) THROW; strcpy (szName, ""); sscanf (sLine, "\"%[^\"]\"", szName); strcpy( Bone.szParentName, szName ); // flags, position, rotation RageVector3 Position, Rotation; if( f.GetLine( sLine ) <= 0 ) THROW; int nFlags; if (sscanf (sLine, "%d %f %f %f %f %f %f", &nFlags, &Position[0], &Position[1], &Position[2], &Rotation[0], &Rotation[1], &Rotation[2]) != 7) { THROW; } Rotation = RadianToDegree(Rotation); Bone.nFlags = nFlags; memcpy( &Bone.Position, &Position, sizeof(Bone.Position) ); memcpy( &Bone.Rotation, &Rotation, sizeof(Bone.Rotation) ); // position key count if( f.GetLine( sLine ) <= 0 ) THROW; int nNumPositionKeys = 0; if (sscanf (sLine, "%d", &nNumPositionKeys) != 1) THROW; Bone.PositionKeys.resize( nNumPositionKeys ); for( int j = 0; j < nNumPositionKeys; ++j ) { if( f.GetLine( sLine ) <= 0 ) THROW; float fTime; if (sscanf (sLine, "%f %f %f %f", &fTime, &Position[0], &Position[1], &Position[2]) != 4) THROW; msPositionKey key; key.fTime = fTime; key.Position = RageVector3( Position[0], Position[1], Position[2] ); Bone.PositionKeys[j] = key; } // rotation key count if( f.GetLine( sLine ) <= 0 ) THROW; int nNumRotationKeys = 0; if (sscanf (sLine, "%d", &nNumRotationKeys) != 1) THROW; Bone.RotationKeys.resize( nNumRotationKeys ); for( int j = 0; j < nNumRotationKeys; ++j ) { if( f.GetLine( sLine ) <= 0 ) THROW; float fTime; if (sscanf (sLine, "%f %f %f %f", &fTime, &Rotation[0], &Rotation[1], &Rotation[2]) != 4) THROW; Rotation = RadianToDegree(Rotation); msRotationKey key; key.fTime = fTime; key.Rotation = RageVector3( Rotation[0], Rotation[1], Rotation[2] ); Bone.RotationKeys[j] = key; } } // Ignore "Frames:" in file. Calculate it ourself Animation.nTotalFrames = 0; for( int i = 0; i < (int)Animation.Bones.size(); i++ ) { msBone& Bone = Animation.Bones[i]; for( unsigned j = 0; j < Bone.PositionKeys.size(); ++j ) Animation.nTotalFrames = max( Animation.nTotalFrames, (int)Bone.PositionKeys[j].fTime ); for( unsigned j = 0; j < Bone.RotationKeys.size(); ++j ) Animation.nTotalFrames = max( Animation.nTotalFrames, (int)Bone.RotationKeys[j].fTime ); } } return bLoaded; }
TEST(Common, Dirname) { EXPECT_EQ(Dirname("/path/to/filename"), "/path/to"); EXPECT_EQ(Dirname("path/to/filename"), "path/to"); EXPECT_EQ(Dirname("/path/to/filename.txt"), "/path/to"); EXPECT_EQ(Dirname("path/to/filename.txt"), "path/to"); }
/* ------------------------------------------------------------- * link: Create a hard link between 2 files * Usage: link oldfile newfile * * (1) get INODE of oldfile into memory * (2) check that oldfile is file, not DIR * (3) check newfile's parent directory exists but newfile * doesn't exist in it * (4) Add an entry to the data block of newfile's parent * with same ino as oldfile * (5) increment the i_links of INODE by 1 * (6) write INODE back to disk ------------------------------------------------------------------*/ void link_(char** args) { char* oldPath, *newPath; // I.e., /a/b/c and /x/y/z int oldino, newPino; // Ino of /a/b/c and /x/y !! int i; int dev = running->cwd->dev; MINODE* omip, *ndp; // oldPath, newDirectoryParent (/x/y) char buf[BLOCK_SIZE]; char* cp; DIR* dp; char nameBuff[256]; // Link requires two arguments, if either are NULL inform user if(args[0] == NULL || args[1] == NULL) { printf("Error: link requires two pathnames\n"); return; } oldPath = strdup(args[0]); // Copy names newPath = strdup(args[1]); printf("Creating link from old file (%s) to new file (%s)....\n", oldPath, newPath); // (1) Get INODE of oldfile ("/a/b/c") into memory oldino = getino(&dev, oldPath); // get ino omip = iget(dev, oldino); // get MINODE* if(omip == NULL) { printf("Error: could not find file %s\n", args[0]); return; } if(!isreg(omip)) // (2) Check that oldfile is a file, not DIR { printf("Error: cannot link directories \n"); iput(omip); return; } // (3) check newfile's parent directory exists but newfile // doesn't exist in it newPino = getino(&dev, Dirname(newPath)); // get ino to "/x/y" ndp = iget(dev, newPino); if(ndp == NULL) { printf("Error: could not find directory %s\n", Dirname(newPath)); return; } else if(!isdir(ndp)) { printf("Error: %s is not a directory\n", Dirname(newPath)); iput(ndp); return; } else if(search(ndp, Basename(newPath))!=0) // Search for 'z' in /x/y { printf("Error: %s already exists in %s\n", Basename(newPath), Dirname(newPath)); iput(ndp); return; } /* (4) Now add a new entry to ndp's data block with same ino as oldfile */ my_creat(ndp, Basename(newPath)); // The entry has been created in ndp's data blocks // Now we've got to find it and change it's ino for(i=0; i<12; i++) { if(ndp->INODE.i_block[i] != 0) { // Read i_blocks into buf get_block(dev, ndp->INODE.i_block[i], buf); cp = buf; // points to start of buf dp = (DIR *)cp; while(cp < &buf[BLOCK_SIZE]) { strncpy(nameBuff, dp->name, dp->name_len); nameBuff[dp->name_len] = 0; if(strcmp(nameBuff, Basename(newPath)) == 0) { // Found the entry, change it's inode dp->inode = oldino; put_block(dev, ndp->INODE.i_block[i], buf); } cp += dp->rec_len; // go to next entry dp = (DIR *)cp; } } } iput(ndp); omip->INODE.i_links_count++; // (5) Increment link count of oldfile omip->dirty =1 ; iput(omip); //(6) write INODE back to disk }
/*----------------------------------------------------------------------- * unklink: Remove the link between two files * (1) get /a/b/c's INODE into memory * ino = iget(dev, filename); * rm = getino(dev, ino); * (2) Verify that rm is a file (NOT DIR) * (3) Decrement rm->INODE's link count by 1 * (4) If rm->links_count == 1, remove the file * Deallocate data blocks * Deallocate INODE * (5) Remove c from directory by * rm_child(rm, 'c') -----------------------------------------------------------------------*/ void ulink(char** args) { MINODE* rm; MINODE* parent; char* filename; int dev, ino, pino; int i; if(args[0] == NULL) { printf("Error: unlink requires a pathname\n"); return; } filename = strdup(args[0]); // (1) Load MINODE of file to be unlinked ino = getino(&dev, filename); // get it's inumber rm = iget(dev, ino); // and load the MINODE if(rm == NULL) { printf("Error: Invalid path %s\n", filename); return; } // (2) Verify file is regular (not DIR) if(!isreg(rm)) { printf("Error: unlink cannot be used on directories \n"); iput(rm); return; } rm->INODE.i_links_count--; // (3) Decrement links count dev = rm->dev; ino = rm->ino; // No remaining links if(rm->INODE.i_links_count < 1) { // Deallocate datablocks for(i=0; i<12; i++) bdealloc(dev, rm->INODE.i_block[i]); // Deallocate inode for(i=0; i<12; i++) idealloc(dev, ino); } // Remove from parent directory pino = getino(&dev, Dirname(filename)); // parent's directory parent = iget(dev, pino); // Remove child from parent's data blocks rm_child(parent, Basename(filename)); parent->dirty = 1; rm->dirty = 1; iput(parent); iput(rm); }
std::string GetExecutableDirectory() { return Dirname(GetExecutablePath()); }