Пример #1
0
int main(int argc, char **argv)
{
	struct dirent *dentp;
	DIR *dp;
	char buf[BUFLEN+2];

	if (argc < 2) {
		fprintf(stderr, "Usage: %s dir1 dir2 ... dirN\n", argv[0]);
		return 1;
	}


	while (--argc >= 1) {
		if ((dp = opendir(argv[argc])) == NULL) {
			fprintf(stderr, "Cannot open directory %s\n",
				argv[argc]);
			return 2;
		}
		while ((dentp = readdir(dp)) != NULL) {
			snprintf(buf, BUFLEN, "%s/%s", argv[argc],
				 dentp->d_name);
			if(notdot(dentp->d_name)) 
			  nodeinfo(buf);
		}

		while ((closedir(dp) == -1) && (errno == EINTR));
	}
	return 0;


}
Пример #2
0
QIcon QFileIconProviderPrivate::getHaikuIcon(const QFileInfo &fi) const
{
    QIcon retIcon;
    
	BNode node(fi.canonicalFilePath().toUtf8().constData());
	if (node.InitCheck() == B_OK) {
		BNodeInfo nodeinfo(&node);
		
		BBitmap *hIcon = new BBitmap(BRect(0, 0, 15, 15), B_RGBA32);
		nodeinfo.GetTrackerIcon(hIcon, B_MINI_ICON);
		if(hIcon) {
			QPixmap p = QPixmap::fromHaikuBitmap(hIcon);
			retIcon.addPixmap(p);
			delete hIcon;
		}

		BBitmap *hIconBig = new BBitmap(BRect(0, 0, 31, 31), B_RGBA32);
		nodeinfo.GetTrackerIcon(hIcon, B_LARGE_ICON);
		if(hIconBig) {
			QPixmap p = QPixmap::fromHaikuBitmap(hIconBig);
			retIcon.addPixmap(p);
			delete hIconBig;
		}		
	}	
    return retIcon;
}
Пример #3
0
bool PeepsWindow::IsPerson(entry_ref ref)
{
	BNode node(&ref);
	BNodeInfo nodeinfo(&node);
	char type[255];
	
	nodeinfo.GetType(type);
	
	if(strcmp(type,PERSON_FILE_TYPE)==0)
		return true;

	return false;
}
Пример #4
0
void nodeinfo(const char *node)
{
	struct stat statb;
        struct dirent *dentp;
	DIR *dp;
        char buf[BUFLEN+2];
	char tbuf[30];

	if (lstat(node, &statb) == -1) {
		fprintf(stderr, "Error getting status for %s \n", node);
		if (errno == EBADF)
			fprintf(stderr, "filedes is bad");
		if (errno == ENOENT)
			fprintf(stderr, "component does not exist");
		if (errno == ENOTDIR)
			fprintf(stderr, "component of path not dir");
		if (errno == EACCES)
			fprintf(stderr, " Permission denied");
		if (errno == ENOMEM)
			fprintf(stderr, " Out of memory");
		if (errno == ENAMETOOLONG)
			fprintf(stderr, " File name too long");
	} else {




		strftime(tbuf,30,"%Y-%m-%d %T",localtime(&statb.st_atime));
                printf("%s a %s", node,tbuf);

		strftime(tbuf,30,"%Y-%m-%d %T",localtime(&statb.st_mtime));
		printf(",m %s", tbuf);

		strftime(tbuf,30,"%Y-%m-%d %T",localtime(&statb.st_ctime));
		printf(",s %s",tbuf);


		printf(",s# %ld", statb.st_ino);
		printf(",size(bytes) %ld", statb.st_size);

                printf(",mode %o",statb.st_mode);
                printf(",nlink %d",statb.st_nlink);
                printf(",devid %d",(int)statb.st_dev);
                printf(",uid %d",statb.st_uid);
                printf(",gid %d\n",statb.st_gid);

                if (S_ISDIR(statb.st_mode) )
		  {
		    printf("  directory %s\n",node);
                    if ((dp = opendir(node)) == NULL) {
		      fprintf(stderr," (node:Cannot open directory %s) ",node);
		    }else {
                      while((dentp = readdir(dp)) != NULL) {
			if(notdot(dentp->d_name)) {  
                          snprintf(buf,BUFLEN,"%s/%s",node,dentp->d_name);
			  nodeinfo(buf);
			}
		      }
              		while ((closedir(dp) == -1) && (errno == EINTR));
                   }
 
                  }
	}
}
Пример #5
0
bool Application::initialize( int argc, char **argv )
{
    // this is used when hunting for memory leaks
#ifdef YAF3D_ENABLE_HEAPCHECK
    // trigger debugger
    //__asm int 3;
#endif

    std::string arg_levelname;
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments( &argc,argv );
    osg::ArgumentParser::Parameter levelparam( arg_levelname );
    arguments.read( "-level", arg_levelname ); // read the level file if one given

    int   argpos;
    // set proper game mode
    GameState::get()->setMode( GameState::Standalone );
    if ( ( argpos = arguments.find( "-server" ) ) != 0 )
    {
        GameState::get()->setMode( GameState::Server );
        arguments.remove( argpos );
    }
    else if ( ( argpos = arguments.find( "-client" ) ) != 0 )
    {
        GameState::get()->setMode( GameState::Client );
        arguments.remove( argpos );
    }

    // note: before beginning to initialize the framework modules the media path must be set, 
    //  other modules need it for loading resources etc.
    //-------------------
    std::vector< std::string > path;
    std::string dir;
    {
        char* p_env = getenv( YAF3D_ENV_MEDIA_DIR );
        if ( p_env )
        {
            _mediaPath = p_env;
        }
        else
        {
            dir = getCurrentWorkingDirectory();
            dir = cleanPath( dir );
            dir += "/";
            path.clear();
            explode( dir, "/", &path );
#ifdef LINUX
            dir = "/";
#endif
#ifdef WIN32
            dir = "";
#endif
            for ( size_t cnt = 0; cnt < path.size() - 2; ++cnt )
                dir += path[ cnt ] + "/";

            dir.erase( dir.size() -1 );
            _mediaPath = dir;
            _mediaPath += YAF3D_MEDIA_PATH;
        }
    }

    //-------------------
    // set the ful binary path of application
    _fulBinaryPath = arguments.getApplicationName();
    _fulBinaryPath = cleanPath( _fulBinaryPath );
    _fulBinaryPath = _fulBinaryPath.substr( 0, _fulBinaryPath.rfind( '/' ) );
    //-------------------

    // load the standard configuration before changing to 'Initializing' state
    Configuration::get()->load();

    // set game state
    _p_gameState->setState( GameState::Initializing );

    // setup log system
    {
        std::string loglevel;
        bool        invalidloglevel = false;
        Log::Level  level           = Log::L_ERROR;

        // get the log level from configuration
        Configuration::get()->getSettingValue( YAF3D_GS_LOG_LEVEL, loglevel );

        if ( loglevel == "error" )
            level = Log::L_ERROR;
        else if ( loglevel == "warning" )
            level = Log::L_WARNING;
        else if ( loglevel == "debug" )
            level = Log::L_DEBUG;
        else if ( loglevel == "info" )
            level = Log::L_INFO;
        else 
            invalidloglevel = true;

        // create log sinks with configured log level
        if ( GameState::get()->getMode() != GameState::Server )
            log.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME ), level );
        else
            log.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME_SERVER ), level );

        // only the server needs an console stdout
#ifdef YAF3D_HAS_CONSOLE
        log.addSink( "stdout", std::cout, level );
#endif

        // check if we have to report an invalid log level in configuration
        if ( invalidloglevel )
            log_warning << "Application: configuration contains an invalid log level, possible values are: error, warning, debug, info. set to error." << std::endl;
    }

    log.enableSeverityLevelPrinting( false );
    log_info << std::endl;
    log << " *******************************************"    << std::endl;
    log << " * yaf3d -- Yet another Framework 3D       *"    << std::endl;
    log << " * version: " << std::string( YAF3D_VERSION ) << "                          *"  << std::endl;
    log << " * project: Yag2002                        *"    << std::endl;
    log << " * site:    http://yag2002.sourceforge.net *"    << std::endl;
    log << " * contact: [email protected]               *"    << std::endl;
    log << " *******************************************"    << std::endl;
    log << "" << std::endl;
    log.enableSeverityLevelPrinting( true );

    log << "Application: time " << yaf3d::getTimeStamp();

    // print cpu info
    {
        std::stringstream cpuinfo;
        cpuinfo << "Application: CPU supports ";
        if ( SDL_HasRDTSC() ) 
            cpuinfo << "RDTSC ";
        if ( SDL_HasMMX() ) 
            cpuinfo << "MMX ";
        if ( SDL_HasMMXExt() ) 
            cpuinfo << "MMXExt ";
        if ( SDL_Has3DNow() ) 
            cpuinfo << "3DNow ";
        if ( SDL_Has3DNowExt() ) 
            cpuinfo << "3DNowExt ";
        if ( SDL_HasSSE() ) 
            cpuinfo << "SSE ";
        if ( SDL_HasSSE2() ) 
            cpuinfo << "SSE2 ";
        if ( SDL_HasAltiVec() ) 
            cpuinfo << "AltiVec ";

        log << cpuinfo.str() << std::endl;
    }

    log << "Application: initializing viewer" << std::endl;
    log << "Application: using media path: " << _mediaPath << std::endl;

    // setup the viewer
    //----------
    
    // load the display settings
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENWIDTH,  _screenWidth  );
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENHEIGHT, _screenHeight );
    Configuration::get()->getSettingValue( YAF3D_GS_FULLSCREEN,   _fullScreen   );
    unsigned int colorBits = 24;
    Configuration::get()->getSettingValue( YAF3D_GS_COLORBITS, colorBits );

    // init SDL
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE );
    // set the icon and caption title
    SDL_WM_SetCaption( YAF3D_APP_TITLE, NULL );
    SDL_Surface* p_bmpsurface = SDL_LoadBMP( YAF3D_APP_ICON );
    if ( p_bmpsurface )
    {
        Uint32 col = SDL_MapRGB( p_bmpsurface->format, 255, 255, 255 );
        SDL_SetColorKey( p_bmpsurface, SDL_SRCCOLORKEY, col );
        SDL_WM_SetIcon( p_bmpsurface, NULL );
    }
    // enable unicode translation
    SDL_EnableUNICODE( 1 ); 
    SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL ); // enable key repeating

    _p_viewer = new osgSDL::Viewer;
    _rootSceneNode = new osg::Group;
    _rootSceneNode->setName( "_topSceneGroup_" );
	osgSDL::Viewport*   p_viewport = new osgSDL::Viewport( _rootSceneNode.get() );
	osgUtil::SceneView* p_sceneView = p_viewport->getSceneView();
    p_sceneView->setDefaults( osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT );
	_p_viewer->addViewport( p_viewport );
    _p_viewer->requestContinuousUpdate( true ); // force event generation for FRAMEs, we need this for animations, etc.
    int flags = SDL_HWSURFACE;
    if ( _fullScreen )
        flags |= SDL_FULLSCREEN;
    if ( GameState::get()->getMode() == GameState::Server )
    {
        SDL_WM_SetCaption( YAF3D_APP_TITLE "-server", NULL );
    }
  	_p_viewer->setDisplayMode( _screenWidth, _screenHeight, colorBits, flags );
    _p_viewer->setCursorEnabled( false );    
    //------------

    // setup keyboard map
    std::string keybType;
    Configuration::get()->getSettingValue( YAF3D_GS_KEYBOARD, keybType );
    log_info << "Application: setup keyboard map to: " << keybType << std::endl;
    if ( keybType == YAF3D_GS_KEYBOARD_ENGLISH )
        KeyMap::get()->setup( KeyMap::English );
    else
        KeyMap::get()->setup( KeyMap::German );

    // get the instance of gui manager
    _p_guiManager = GuiManager::get();
    // setup networking
    _p_networkDevice = NetworkDevice::get();
    // avoid creating of remote clients so long we are initializing the system
    _p_networkDevice->lockObjects();
    if ( GameState::get()->getMode() == GameState::Server )
    {
        log_info << "Application: loading level file '" << arg_levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( YAF3D_LEVEL_SERVER_DIR + arg_levelname );
        if ( !sceneroot.valid() )
            return false;

        // start networking before setting up entities
        std::string servername;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_NAME, servername );
        NodeInfo nodeinfo( arg_levelname, servername );
        unsigned int channel;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup server
        try
        {
            _p_networkDevice->setupServer( channel, nodeinfo );
        }
        catch ( const NetworkExpection& e )
        {
            log_error << "Application: error starting server, reason: " << e.what() << std::endl;
            return false;
        }

        // complete level loading
        LevelManager::get()->finalizeLoading();

        // the server needs no drawing
        _p_viewer->setUpdateAllViewports( false );
    }
    else if ( GameState::get()->getMode() == GameState::Client )
    {
        std::string url;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_IP, url );
        std::string clientname( "vrc-client" );
        NodeInfo nodeinfo( "", clientname );
        unsigned int channel;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup client networking
        try
        {
            _p_networkDevice->setupClient( url, channel, nodeinfo );
        }
        catch ( const NetworkExpection& e )
        {
            log_error << "Application: error setting up client networking, reason: " << e.what() << std::endl;
            return false;
        }

        // now load level
        std::string levelname = YAF3D_LEVEL_CLIENT_DIR + _p_networkDevice->getNodeInfo()->getLevelName();
        log_info << "Application: loading level file '" << levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( levelname );
        if ( !sceneroot.valid() )
            return false;
        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a client with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
        EntityManager::get()->sendNotification( notification );
    }
    else // check for any level file name, so we try to start in Standalone mode
    {
        std::string defaultlevel = arg_levelname.length() ? ( std::string( YAF3D_LEVEL_SALONE_DIR ) + arg_levelname ) : std::string( YAF3D_DEFAULT_LEVEL );
        log_info << "Application: loading level file '" << defaultlevel << "'" << std::endl;
        // set game mode
        GameState::get()->setMode( GameState::Standalone );
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( defaultlevel );
        if ( !sceneroot.valid() )
            return false;
        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a client with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
        EntityManager::get()->sendNotification( notification );
    }

    return true;
}
Пример #6
0
bool Application::initialize( int argc, char **argv )
{
    // this is used when hunting for memory leaks
#ifdef YAF3D_ENABLE_HEAPCHECK
    // trigger debugger
    //__asm int 3;
#endif

    //! NOTE: on multi-core systems running win32, sometimes a noticable performance drop has been observed
    //        when the application uses more than one cpu for its threads. here we assign only one cpu to the entire app.
#ifdef WIN32
    SYSTEM_INFO sysInfo;
    GetSystemInfo( &sysInfo );
    if ( sysInfo.dwNumberOfProcessors > 1 )
    {
        // take the first cpu for our application
        DWORD_PTR  processAffinityMask = 0x1;
        SetProcessAffinityMask( GetCurrentProcess(), processAffinityMask );
    }
#endif

    // seed the standard pseudo random generator
    time_t t = time( NULL );
    srand( static_cast< unsigned int >( t ) );

    std::string arg_levelname;
    bool        arg_nodefaultlvl = false;
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments( &argc,argv );
    osg::ArgumentParser::Parameter levelparam( arg_levelname );
    arguments.read( "-level", arg_levelname ); // read the level file if one given

    int   argpos;
    // set proper game mode
    GameState::get()->setMode( GameState::Standalone );
    if ( ( argpos = arguments.find( "-server" ) ) > 0 )
    {
        GameState::get()->setMode( GameState::Server );
        arguments.remove( argpos );
    }
    else if ( ( argpos = arguments.find( "-client" ) ) > 0 )
    {
        GameState::get()->setMode( GameState::Client );
        arguments.remove( argpos );
    }
    if ( ( argpos = arguments.find( "-nodefaultlevel" ) ) > 0 )
    {
        arg_nodefaultlvl = true;
        arguments.remove( argpos );
    }

    // note: before beginning to initialize the framework modules the media path must be set,
    //  other modules need it for loading resources etc.
    //-------------------
    std::vector< std::string > path;
    std::string dir;
    {
        char* p_env = getenv( YAF3D_ENV_MEDIA_DIR );
        if ( p_env )
        {
            _mediaPath = p_env;
        }
        else
        {
            dir = getCurrentWorkingDirectory();
            dir = cleanPath( dir );
            dir += "/";
            path.clear();
            explode( dir, "/", &path );
#ifdef LINUX
            dir = "/";
#endif
#ifdef WIN32
            dir = "";
#endif
            for ( size_t cnt = 0; cnt < path.size() - 2; ++cnt )
                dir += path[ cnt ] + "/";

            dir.erase( dir.size() -1 );
            _mediaPath = dir;
            _mediaPath += YAF3D_MEDIA_PATH;
        }
    }

    //-------------------
    // set the ful binary path of application
    _fulBinaryPath = arguments.getApplicationName();
    _fulBinaryPath = cleanPath( _fulBinaryPath );
    _fulBinaryPath = _fulBinaryPath.substr( 0, _fulBinaryPath.rfind( '/' ) );
    //-------------------

    // load the standard configuration before changing to 'Initializing' state
    Configuration::get()->load();

    // set game state
    _p_gameState->setState( GameState::Initializing );

    // setup log system
    {
        std::string loglevel;
        Log::Level  level = Log::L_ERROR;

        // get the log level from configuration
        Configuration::get()->getSettingValue( YAF3D_GS_LOG_LEVEL, loglevel );

        // check if we have to report an invalid log level in configuration
        if ( loglevel == "error" )
            level = Log::L_ERROR;
        else if ( loglevel == "warning" )
            level = Log::L_WARNING;
        else if ( loglevel == "debug" )
            level = Log::L_DEBUG;
        else if ( loglevel == "info" )
            level = Log::L_INFO;
        else if ( loglevel == "verbose" )
            level = Log::L_VERBOSE;
        else
            log_warning << "Application: configuration contains an invalid log level, possible values are: error, warning, debug, info, verbose. set to error." << std::endl;

        // create log sinks with configured log level
        if ( GameState::get()->getMode() != GameState::Server )
            log_out.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME ), level );
        else
            log_out.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME_SERVER ), level );

        // only the server needs an console stdout
#ifdef YAF3D_HAS_CONSOLE
        log_out.addSink( "stdout", std::cout, level );
#endif

    }

    log_out.enableSeverityLevelPrinting( false );
    log_info << std::endl;
    log_out << " *******************************************"    << std::endl;
    log_out << " * yaf3d -- Yet another Framework 3D       *"    << std::endl;
    log_out << " * version: " << std::string( YAF3D_VERSION ) << "                          *"  << std::endl;
    log_out << " * project: Yag2002                        *"    << std::endl;
    log_out << " * site:    http://yag2002.sourceforge.net *"    << std::endl;
    log_out << " * contact: [email protected] *"    << std::endl;
    log_out << " *******************************************"    << std::endl;
    log_out << "" << std::endl;
    log_out.enableSeverityLevelPrinting( true );

    log_out << "Application: time " << yaf3d::getTimeStamp();

    // print cpu info
    {
        std::stringstream cpuinfo;
        cpuinfo << "Application: CPU supports ";
        if ( SDL_HasRDTSC() )
            cpuinfo << "RDTSC ";
        if ( SDL_HasMMX() )
            cpuinfo << "MMX ";
        if ( SDL_HasMMXExt() )
            cpuinfo << "MMXExt ";
        if ( SDL_Has3DNow() )
            cpuinfo << "3DNow ";
        if ( SDL_Has3DNowExt() )
            cpuinfo << "3DNowExt ";
        if ( SDL_HasSSE() )
            cpuinfo << "SSE ";
        if ( SDL_HasSSE2() )
            cpuinfo << "SSE2 ";
        if ( SDL_HasAltiVec() )
            cpuinfo << "AltiVec ";

        log_out << cpuinfo.str() << std::endl;
    }

    // implement the signal handler
    implementSignalHandler();

    log_out << "Application: using media path: " << _mediaPath << std::endl;
    log_out << "Application: setup virtual file system" << std::endl;

    try
    {
        FileSystem::get()->initialize( argv );
        FileSystem::get()->mountResource( _mediaPath, "/" );
        if ( fileExists( _mediaPath + YAF3D_MEDIA_PACK ) )
        {
            FileSystem::get()->mountResource( _mediaPath + YAF3D_MEDIA_PACK, "/" );
        }
    }
    catch ( const FileSystemException& e )
    {
        log_error << "Application: problem occured while setting up the virtual file system!" << std::endl;
        log_error << " reason:" << e.what() << std::endl;
        return false;
    }

    // setup the viewer
    //----------

    // load the display settings
    log_out << "Application: initializing viewer" << std::endl;
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENWIDTH,  _screenWidth  );
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENHEIGHT, _screenHeight );
    Configuration::get()->getSettingValue( YAF3D_GS_FULLSCREEN,   _fullScreen   );
    unsigned int colorBits = 24;
    Configuration::get()->getSettingValue( YAF3D_GS_COLORBITS, colorBits );

    // set the icon and caption title only for non-servers
    if ( GameState::get()->getMode() != GameState::Server )
    {
       // init SDL with video
        SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE );

        // set application window's title
        _appWindowTitle = YAF3D_APP_TITLE " " YAF3D_VERSION;
        setWindowTitle( _appWindowTitle );

        SDL_Surface* p_bmpsurface = SDL_LoadBMP( YAF3D_APP_ICON );
        if ( p_bmpsurface )
        {
            Uint32 col = SDL_MapRGB( p_bmpsurface->format, 255, 255, 255 );
            SDL_SetColorKey( p_bmpsurface, SDL_SRCCOLORKEY, col );
            SDL_WM_SetIcon( p_bmpsurface, NULL );
        }
    }
    else
    {
        // init SDl witout video for server
        SDL_Init( SDL_INIT_NOPARACHUTE );
    }
    // enable unicode translation
    SDL_EnableUNICODE( 1 );
    SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL ); // enable key repeating

    _p_viewer = new osgSDL::Viewer;
    _rootSceneNode = new osg::Group;
    _rootSceneNode->setName( "_topSceneGroup_" );
    osgSDL::Viewport*   p_viewport = new osgSDL::Viewport( _rootSceneNode.get() );
    osgUtil::SceneView* p_sceneView = p_viewport->getSceneView();
    p_sceneView->setDefaults( osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT );
    _p_viewer->addViewport( p_viewport );
    _p_viewer->requestContinuousUpdate( true ); // force event generation for FRAMEs, we need this for animations, etc.

    int flags = SDL_HWSURFACE;
    if ( _fullScreen )
        flags |= SDL_FULLSCREEN;

    _p_viewer->setDisplayMode( _screenWidth, _screenHeight, colorBits, flags );
    _p_viewer->setCursorEnabled( false );
    //------------

    // setup keyboard map
    std::string keybType;
    Configuration::get()->getSettingValue( YAF3D_GS_KEYBOARD, keybType );
    log_info << "Application: setup keyboard map to: " << keybType << std::endl;
    if ( keybType == YAF3D_GS_KEYBOARD_ENGLISH )
        KeyMap::get()->setup( KeyMap::English );
    else
        KeyMap::get()->setup( KeyMap::German );

    // get the instance of gui manager
    _p_guiManager = GuiManager::get();

    // setup networking
    _p_networkDevice = NetworkDevice::get();
    if ( GameState::get()->getMode() == GameState::Server )
    {
        log_info << "Application: loading level file '" << arg_levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( YAF3D_LEVEL_SERVER_DIR + arg_levelname );
        if ( !sceneroot.valid() )
        {
            log_error << "Application: could not load level '" << YAF3D_LEVEL_SERVER_DIR + arg_levelname << "'" << std::endl;
            return false;
        }

        // append the level node to scene root node
        _rootSceneNode->addChild( sceneroot.get() );

        // start networking before setting up entities
        std::string servername;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_NAME, servername );
        NodeInfo nodeinfo( arg_levelname, servername );
        unsigned int channel = 0;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );
        bool needsAuth = false;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_AUTH, needsAuth );
        nodeinfo.setNeedAuthentification( needsAuth );

        // try to setup server
        try
        {
            _p_networkDevice->setupServer( channel, nodeinfo );
        }
        catch ( const NetworkException& e )
        {
            log_error << "Application: error starting server, reason: " << e.what() << std::endl;
            return false;
        }

        // complete level loading
        LevelManager::get()->finalizeLoading();

        // the server needs no drawing
        _p_viewer->setUpdateAllViewports( false );
    }
    else if ( GameState::get()->getMode() == GameState::Client )
    {
        std::string url;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_IP, url );
        std::string clientname( "vrc-client" );
        NodeInfo nodeinfo( "", clientname );
        unsigned int channel = 0;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup client networking
        try
        {
            _p_networkDevice->setupClient( url, channel, nodeinfo );
        }
        catch ( const NetworkException& e )
        {
            log_error << "Application: error setting up client networking, reason: " << e.what() << std::endl;
            return false;
        }

        // now load level
        std::string levelname = YAF3D_LEVEL_CLIENT_DIR + nodeinfo.getLevelName();
        log_info << "Application: loading level file '" << levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( levelname );
        if ( !sceneroot.valid() )
        {
            log_error << "Application: could not load level '" << levelname << "'" << std::endl;
            return false;
        }

        // append the level node to scene root node
        _rootSceneNode->addChild( sceneroot.get() );

        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a client with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
        EntityManager::get()->sendNotification( notification );
    }
    else if ( !arg_nodefaultlvl ) // check for any level file name, so we try to start in Standalone mode if not no-default-level option is given
    {
        std::string defaultlevel = arg_levelname.length() ? ( std::string( YAF3D_LEVEL_SALONE_DIR ) + arg_levelname ) : std::string( YAF3D_DEFAULT_LEVEL );
        log_info << "Application: loading level file '" << defaultlevel << "'" << std::endl;
        // set game mode
        GameState::get()->setMode( GameState::Standalone );
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( defaultlevel );
        if ( !sceneroot.valid() )
        {
            log_error << "Application: could not load level '" << defaultlevel << "'" << std::endl;
            return false;
        }

        // append the level node to scene root node
        _rootSceneNode->addChild( sceneroot.get() );

        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a level with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        if ( arg_levelname.length() )
        {
            EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
            EntityManager::get()->sendNotification( notification );
        }
    }

    if ( arg_nodefaultlvl )
    {
        // set game mode to standalone
        GameState::get()->setMode( GameState::Standalone );

        // setup the level manager
        LevelManager::get()->finalizeLoading();
        // setup the root node
        _rootSceneNode->addChild( LevelManager::get()->getTopNodeGroup().get() );
    }

    // setup the shadow mananger now
    if ( GameState::get()->getMode() != GameState::Server )
    {
        bool shadow = true;
        // if glsl is not available then disable dynamic shadow flag in configuration
        if ( !yaf3d::isGlslAvailable() )
        {
            log_info << "Dynamic shadows disabled as GLSL is not available!" << std::endl;
            shadow = false;
            yaf3d::Configuration::get()->setSettingValue( YAF3D_GS_SHADOW_ENABLE, shadow );
            yaf3d::Configuration::get()->store();
        }

        bool shadowEnable = false;
        Configuration::get()->getSettingValue( YAF3D_GS_SHADOW_ENABLE, shadowEnable );

        if ( shadow && shadowEnable )
        {
            unsigned int shadowTexSizeX = 0, shadowTexSizeY = 0, shadowTexChannel = 0;
            yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SHADOW_TEXSIZEX, shadowTexSizeX );
            yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SHADOW_TEXSIZEY, shadowTexSizeY );
            yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SHADOW_TEXCHANNEL, shadowTexChannel );
            ShadowManager::get()->setup( shadowTexSizeX, shadowTexSizeY, shadowTexChannel );
        }
    }

    // store sound manager reference for faster access in loop
    _p_soundManager = SoundManager::get();

    // from now on game state can handle application window state changes
    _p_gameState->initAppWindowStateHandler();

    // setup local app window state handler
    _p_appWindowStateHandler = new AppWindowStateHandler( this );

    return true;
}
Пример #7
0
bool EnMenu::onClickedJoin( const CEGUI::EventArgs& /*arg*/ )
{
    // play mouse click sound
    gameutils::GuiUtils::get()->playSound( GUI_SND_NAME_CLICK );

    // check if the client is configured to need authentification
    bool needauth = false;
    yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SERVER_AUTH, needauth );

    if ( needauth )
    {
        // bring up the login dialog
        _loginDialog->enable( true );

        _p_menuWindow->disable();

        return true;
    }

    bool accessDenied = false;

    std::string url;
    yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SERVER_IP, url );

    std::string clientname;
    yaf3d::Configuration::get()->getSettingValue( VRC_GS_PLAYER_NAME, clientname );

    unsigned int channel = 0;
    yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

    yaf3d::NodeInfo nodeinfo( "", clientname );

    _p_loadingWindow->show();

    // if no authentification is needed then directly try to connect the server
    try
    {
        // use empty passwd
        std::string passwd;

        // set the proper game state and mode
        yaf3d::GameState::get()->setMode( yaf3d::GameState::Client ); // first set the mode!
        yaf3d::GameState::get()->setState( yaf3d::GameState::StartingLevel );

        // try to connect to server
        yaf3d::NetworkDevice::get()->setupClient( url, channel, nodeinfo, clientname, passwd );

        if ( !nodeinfo.getAccessGranted() )
        {
            accessDenied = true;
            throw yaf3d::NetworkException( "Access denied! Server needs authentification.\nCheck your configuration." );
        }
    }
    catch ( const yaf3d::NetworkException& e )
    {
        log_warning << "cannot connect to server\n reason: " << e.what() << std::endl;

        // create a call back for Ok button of messagebox
        yaf3d::MessageBoxDialog* p_msg = new yaf3d::MessageBoxDialog( "Attention", e.what(), yaf3d::MessageBoxDialog::OK, true );

        class MsgOkClick: public yaf3d::MessageBoxDialog::ClickCallback
        {
            public:

                explicit                MsgOkClick( EnMenu* p_menu ) : _p_menu( p_menu ) {}

                virtual                 ~MsgOkClick() {}

                void                    onClicked( unsigned int /*btnId*/ )
                                        {
                                            _p_menu->_p_menuWindow->enable();

                                            // hide the loading level overlay
                                            _p_menu->_p_loadingWindow->hide();

                                            // play mouse click sound
                                            vrc::gameutils::GuiUtils::get()->playSound( GUI_SND_NAME_CLICK );
                                        }

                EnMenu*                 _p_menu;
        };
        p_msg->setClickCallback( new MsgOkClick( this ) );
        p_msg->show();

        // play attention sound
        vrc::gameutils::GuiUtils::get()->playSound( GUI_SND_NAME_ATTENTION );

        if ( accessDenied )
            return true;
    }

    // now prepare loading level
    std::string levelfilename;
    if ( nodeinfo.getLevelName().length() )
    {
        levelfilename = nodeinfo.getLevelName();
        _queuedLevelFile = YAF3D_LEVEL_CLIENT_DIR + levelfilename;
    }

    // set the game mode to Client before loading the level
    yaf3d::GameState::get()->setMode( yaf3d::GameState::Client );

    // release level files object
    if ( _p_clientLevelFiles )
        delete _p_clientLevelFiles;

    _p_clientLevelFiles = new gameutils::LevelFiles( YAF3D_LEVEL_CLIENT_DIR );
    CEGUI::Image* p_img = _p_clientLevelFiles->getImage( levelfilename );

    _p_loadingLevelPic->setImage( p_img );
    _p_loadingWindow->show();
    _p_menuWindow->hide();

    _menuState = BeginLoadingLevel;

    return true;
}
Пример #8
0
void EnMenu::onLoginDialogClose( bool btnlogin )
{
    _p_menuWindow->enable();
    _loginDialog->enable( false );

    // cancel button clicked?
    if ( !btnlogin )
        return;

    std::string url;
    yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SERVER_IP, url );
    std::string clientname;
    yaf3d::Configuration::get()->getSettingValue( VRC_GS_PLAYER_NAME, clientname );
    yaf3d::NodeInfo nodeinfo( "", clientname );
    unsigned int channel = 0;
    yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

    // try to join
    bool accessDenied = false;
    try
    {
        // get the details (login and passwd ) from the login dialog and try to login
        std::string login;
        std::string passwd;
        _loginDialog->getAndErazeDetails( login, passwd );

        // set the proper game state and mode
        yaf3d::GameState::get()->setMode( yaf3d::GameState::Client ); // first set the mode!
        yaf3d::GameState::get()->setState( yaf3d::GameState::StartingLevel );

        // try to connect to server
        yaf3d::NetworkDevice::get()->setupClient( url, channel, nodeinfo, login, passwd );

        if ( !nodeinfo.getAccessGranted() )
        {
            accessDenied = true;
            throw yaf3d::NetworkException( "Access denied! Check your login.\nAnother reason can be that someone is\nalready logged in with your account data." );
        }
    }
    catch ( const yaf3d::NetworkException& e )
    {
        log_warning << "cannot connect to server\n reason: " << e.what() << std::endl;

        // create a call back for Ok button of messagebox
        yaf3d::MessageBoxDialog* p_msg = new yaf3d::MessageBoxDialog( "Cannot log in", e.what(), yaf3d::MessageBoxDialog::OK, true );

        class MsgOkClick: public yaf3d::MessageBoxDialog::ClickCallback
        {
            public:

                explicit                MsgOkClick( EnMenu* p_menu ) : _p_menu( p_menu ) {}

                virtual                 ~MsgOkClick() {}

                void                    onClicked( unsigned int /*btnId*/ )
                                        {
                                            _p_menu->_p_menuWindow->enable();

                                            // hide the loading level overlay
                                            _p_menu->_p_loadingWindow->hide();

                                            // play mouse click sound
                                            vrc::gameutils::GuiUtils::get()->playSound( GUI_SND_NAME_CLICK );
                                        }

                EnMenu*                 _p_menu;
        };
        p_msg->setClickCallback( new MsgOkClick( this ) );
        p_msg->show();

        // play attention sound
        vrc::gameutils::GuiUtils::get()->playSound( GUI_SND_NAME_ATTENTION );

        if ( accessDenied )
            return;
    }

    // now prepare loading level
    std::string levelfilename;
    if ( nodeinfo.getLevelName().length() )
    {
        levelfilename = nodeinfo.getLevelName();
        _queuedLevelFile = YAF3D_LEVEL_CLIENT_DIR + levelfilename;
    }

    // set the game mode to Client before loading the level
    yaf3d::GameState::get()->setMode( yaf3d::GameState::Client );

    // release level files object
    if ( _p_clientLevelFiles )
        delete _p_clientLevelFiles;

    _p_clientLevelFiles = new gameutils::LevelFiles( YAF3D_LEVEL_CLIENT_DIR );
    CEGUI::Image* p_img = _p_clientLevelFiles->getImage( levelfilename );

    _p_loadingLevelPic->setImage( p_img );
    _p_loadingWindow->show();
    _p_menuWindow->hide();

    _menuState = BeginLoadingLevel;
}
Пример #9
0
int32 RipView::RipThread(void *data)
{
	acquire_sem(abort_thread);
	
	RipView *view = (RipView*)data;
	
	view->Window()->Lock();
	view->fProgressBar->SetText(_T("Creating songs from CD..."));
	view->Window()->Unlock();
	
	// Get all the preferences that we'll need in one shot to save on piddling
	// around with locking
	prefsLock.Lock();
	
	int16 foldermode;
	if (preferences.FindInt16("foldermode",&foldermode)!=B_OK)
		foldermode=1;
	
	int16 trackname;
	if (preferences.FindInt16("namestyle",&trackname)!=B_OK)
		trackname=0;
	
	int16 bitrate;
	if (preferences.FindInt16("bitrate",&bitrate)!=B_OK)
		bitrate=1;
	
	BString destfolder;
	if (preferences.FindString("path",&destfolder)!=B_OK)
		destfolder="/boot/home/music";
	
	bool use_mp3;
	if (preferences.FindBool("usemp3",&use_mp3)!=B_OK)
		use_mp3=false;
	
	if (use_mp3 && (!gMP3Format || !gMP3Codec))
		use_mp3=false;
	
	bool make_playlist;
	if (preferences.FindBool("makeplaylist",&make_playlist)!=B_OK)
		make_playlist=true;
	
	BString playlistfolder;
	if (preferences.FindString("playlistfolder",&playlistfolder)!=B_OK)
	{
		playlistfolder=destfolder;
		playlistfolder << "/playlists";
	}
	
	prefsLock.Unlock();
	

	bool write_attributes=true;
	
	dev_t destDevice = dev_for_path(destfolder.String());
	BVolume volume(destDevice);
	if (!volume.KnowsAttr())
	{
		write_attributes=false;
		//printf("Volume for %s doesn't support attributes\n",destfolder.String());
	}
	
	// If we are grouping by artist or artist/album, we need to make sure the
	// directory exists
	switch(foldermode)
	{
		case 1:	// Artist
		{
			destfolder << "/" << gCDData.Artist() << "/";
			break;
		}
		case 2: // Album
		{
			destfolder << "/" << gCDData.Album() << "/";
			break;
		}
		case 3: // Artist & Album
		{
			destfolder << "/" << gCDData.Artist() << "/" << gCDData.Album() << "/";
			break;
		}
		default: // no special grouping
		{
			break;
		}
	}
	if (create_directory(destfolder.String(),0777)!=B_OK)
	{
		BEntry dir(destfolder.String());
		if (!dir.Exists())
		{
			BString errormsg;
			#ifdef SYS_ZETA
				errormsg=_T("Uh-oh... SimplyVorbis couldn't create the folder '");
				errormsg << destfolder << _T("RipViewMultiline1");
				
				BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),_T("OK"));
			#else
				errormsg="Uh-oh... SimplyVorbis couldn't create the folder '";
				errormsg << destfolder << "'.\n\nThis may have happened for a number of different reasons, but "
					"most often happens when making music files on a non-BeOS drive, such as one shared "
					"with Windows. Certain characters, such as question marks and slashes cause problems "
					"on these disks. You may want to check the names of the artist, album, and songs for "
					"such characters and put a good substitute in its place or remove the character entirely.";
				
				BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),"OK");
			#endif
			alert->Go();
			
			view->fRipThread = -1;
			view->Window()->PostMessage(M_STOP_ENCODING);
			
			release_sem(abort_thread);
			return 0;
		}
	}
	
	// make the directory only if the user wants to create playlists
	if (make_playlist && create_directory(playlistfolder.String(),0777)!=B_OK)
	{
		BEntry playdir(playlistfolder.String());
		if (!playdir.Exists())
		{
			BString errormsg;
			#ifdef SYS_ZETA			
			errormsg=_T("Uh-oh... SimplyVorbis couldn't create the folder '");
			errormsg << playlistfolder << _T("RIpViewMultiline2");
			
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),_T("OK"));
			#else
			errormsg="Uh-oh... SimplyVorbis couldn't create the folder '";
			errormsg << playlistfolder << "' for the playlists.\n\nThis may have happened for a number of different reasons, but "
				"most often happens when making playlists on a non-BeOS drive, such as one shared "
				"with Windows. Certain characters, such as question marks and slashes cause problems "
				"on these disks. You may want to check the names of the artist, album, and songs for "
				"such characters and put a good substitute in its place or remove the character entirely."
				"For the moment, your music will be created, but the playlist will not. Sorry.";
			
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),"OK");
			#endif
			alert->Go();
			make_playlist=false;
		}
	}
	
	// *Sigh* FAT32 volumes don't support use of question marks. I wonder what else... :(
	if (!write_attributes)
	{
		destfolder.RemoveAll("?");
		playlistfolder.RemoveAll("?");
	}
	
	BString trackPrefix;
	switch(trackname)
	{
		case 0:	// Artist
		{
			trackPrefix = gCDData.Artist();
			trackPrefix+=" - ";
			break;
		}
		case 1: // Album
		{
			trackPrefix = gCDData.Album();
			trackPrefix+=" - ";
			break;
		}
		case 2: // Artist & Album
		{
			trackPrefix = gCDData.Artist();
			trackPrefix << " - " << gCDData.Album() << " - ";
			break;
		}
		default: // no special grouping
		{
			break;
		}
	}
	
	// Populate the list of tracks to be ripped
	view->Window()->Lock();
	
	for(int32 i=view->fRipList->CountItems(); i>0; i--)
	{
		BStringItem *item = (BStringItem *)view->fRipList->RemoveItem(i);
		delete item;
	}
	
	for(int32 i=0; i<gTrackList.CountItems(); i++)
	{
		if (*(gTrackList.ItemAt(i)))
		{
			if (gCDDrive.IsDataTrack(i))
			{
				*(gTrackList.ItemAt(i)) = false;
				continue;
			}
			
			view->fRipList->AddItem(new BStringItem(gCDData.TrackAt(i)));
		}
	}
	view->Window()->Unlock();
	
	// playlists are a nice thing for quite a few people, apparently. :)
	BFile playlistfile;
	BString playlistfilename=playlistfolder;
	
	if (make_playlist)
	{
		playlistfilename << "/" << gCDData.Artist() << " - " << gCDData.Album() << ".m3u";
		
		// Append to playlists instead of overwriting them
		BEntry playlistentry(playlistfilename.String());
		if (playlistentry.Exists())
		{
			if (playlistfile.SetTo(playlistfilename.String(),B_READ_WRITE)==B_OK)
			{
				// HACK: This works around a bug in R5's BFile::Seek implementation
//				playlistfile.Seek(SEEK_END,0);
				off_t filesize;
				playlistfile.GetSize(&filesize);
				if (filesize>0)
				{
					char data[filesize];
					playlistfile.Read(&data,filesize);
				}
			}
			else
				playlistfile.SetTo(playlistfilename.String(),B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE);
		}
		else
			playlistfile.SetTo(playlistfilename.String(),B_READ_WRITE | B_CREATE_FILE);
		
		if (playlistfile.InitCheck()!=B_OK)
		{
			BString errormsg;
			#ifdef SYS_ZETA
			errormsg=_T("Uh-oh... SimplyVorbis couldn't create the playlist '");
			errormsg << playlistfilename << _T("RIpViewMultiline3");
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),_T("OK"));
			#else
			errormsg="Uh-oh... SimplyVorbis couldn't create the playlist '";
			errormsg << playlistfilename << "'.\n\nThis may have happened for a number of different reasons, but "
				"most often happens when making playlists on a non-BeOS drive, such as one shared "
				"with Windows. Certain characters, such as question marks and slashes cause problems "
				"on these disks. You may want to check the names of the artist, album, and songs for "
				"such characters and put a good substitute in its place or remove the character entirely."
				"For the moment, your music will be created, but the playlist will not. Sorry.";
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),"OK");
			#endif	

			alert->Go();
			make_playlist = false;
		}
	}
	
	BString syscmd;
	BMessenger msgr(view);
	bool copyfailed = false;
	bool showfailalert = 0;
	for (int32 i = 0; i < gTrackList.CountItems(); i++)
	{
		if (*(gTrackList.ItemAt(i)))
		{
			view->Window()->Lock();
			BStringItem *oldtrack = (BStringItem*)view->fRipList->RemoveItem(0L);
			view->Window()->Unlock();
			delete oldtrack;
			
			BString filename(trackPrefix);
			filename += gCDData.TrackAt(i);
			
			// FAT32 is such a pain in the neck here. Certain characters which are *just* *fine* for
			// other OSes are illegal. Just for the user's sake, we will constrain ourselves to its limits.
			// This means that question marks, double quotes, and colons will be substituted or removed.
			// Although it has not popped up in testing, backslashes are also substituted just in case
			filename.RemoveSet("?");
			filename.ReplaceAll("/", "-");
			filename.ReplaceAll("\\", "-");
			filename.ReplaceAll("\"", "'");
			filename.ReplaceAll(":", "-");
			
			// Set things up for the progress bar for ripping this particular track
			view->Window()->Lock();
			
			view->fProgressLabel=_T("Converting '");
			view->fProgressLabel << gCDData.TrackAt(i) << "'";
			view->fProgressBar->SetText(view->fProgressLabel.String());
			
			rgb_color blue={50,150,255,255};
			view->fProgressBar->SetBarColor(blue);
			
			cdaudio_time tracklength;
			gCDDrive.GetTimeForTrack(i+1,tracklength);
			view->fProgressBar->SetMaxValue( (tracklength.minutes * 60) + tracklength.seconds);
			view->fProgressDelta = 100.0 / float( (tracklength.minutes * 60) + tracklength.seconds);
			view->fProgressBar->Reset();
			
			view->Window()->Unlock();
			
			BString ripname(filename);
			ripname += use_mp3 ? ".mp3" : ".ogg";
			cdaudio_time rippedtime;
			
			status_t ripstat=B_OK;
			
			if (use_mp3)
				ripstat=ConvertTrack(gCDDrive.GetDrivePath(),ripname.String(),i+1,*gMP3Format,
									*gMP3Codec,&msgr,abort_thread);
			else
				ripstat=VorbifyTrack(gCDDrive.GetDrivePath(),ripname.String(),i+1,&msgr,abort_thread);
			
			if (ripstat==B_INTERRUPTED)
			{
				//  This will unblock the window
				view->fRipThread = -1;
				view->Window()->PostMessage(M_STOP_ENCODING);
				release_sem(abort_thread);
				BEntry entry(ripname.String());
				if (entry.Exists())
					entry.Remove();
				return -1;
			}
			else
			if (ripstat!=B_OK)
			{
				// Because things aren't really accurate on some CDs on the last audio track, 
				// we bear with it.
				if (!gCDDrive.IsDataTrack(i+1))
				{
					view->Window()->Lock();
					view->fProgressBar->SetText(_T("Couldn't read song from the CD. Sorry!"));
					view->Window()->Unlock();
					BEntry entry(ripname.String());
					if (entry.Exists())
						entry.Remove();
					continue;
				}
				else
				{
					view->Window()->Lock();
					rgb_color darkblue={0,0,127,255};
					view->fProgressBar->Update(view->fProgressBar->MaxValue() - 
												view->fProgressBar->CurrentValue(),
												_T("Finishing early. This is not a bad thing."));
					view->fProgressBar->SetBarColor(darkblue);
					view->Window()->Unlock();
					rippedtime = GetTimeRipped();
				}
			}
			else
			{
				view->Window()->Lock();
				rgb_color darkblue={0,0,127,255};
				view->fProgressBar->SetBarColor(darkblue);
				view->Window()->Unlock();
			}
			
			// This will ensure that the drive isn't running for an unnecesary amount of time
			gCDDrive.Stop();
			
			// Set the mime type
			filename=destfolder;
			filename << trackPrefix << gCDData.TrackAt(i) << (use_mp3 ? ".mp3" : ".ogg");
			
			BNode node(ripname.String());
#ifndef FAKE_RIPPING
			if (node.InitCheck()==B_OK)
#endif
			{
				BNodeInfo nodeinfo(&node);
				if (nodeinfo.InitCheck()==B_OK)
					nodeinfo.SetType( use_mp3 ? "audio/x-mpeg" : "audio/x-vorbis");
				
				if (write_attributes)
				{
					if (strlen(gCDData.Genre())>0)
						node.WriteAttr("Audio:Genre",B_STRING_TYPE,0,gCDData.Genre(),strlen(gCDData.Genre())+1);
					node.WriteAttr("Audio:Comment",B_STRING_TYPE,0,"Created by SimplyVorbis",
									strlen("Created by SimplyVorbis")+1);
					node.WriteAttr("Audio:Title",B_STRING_TYPE,0,gCDData.TrackAt(i),
									strlen(gCDData.TrackAt(i))+1);
					node.WriteAttr("Audio:Album",B_STRING_TYPE,0,gCDData.Album(),
									strlen(gCDData.Album())+1);
					node.WriteAttr("Audio:Artist",B_STRING_TYPE,0,gCDData.Artist(),
									strlen(gCDData.Artist())+1);
					
					int32 tracknum = i+1;
					node.WriteAttr("Audio:Track",B_INT32_TYPE,0,(const void *)&tracknum, sizeof(int32));
					
					node.WriteAttr("Audio:Bitrate",B_STRING_TYPE,0,(const void *)"128", strlen("128")+1);
					
					cdaudio_time tracktime;
					if (gCDDrive.GetTimeForTrack(i+1,tracktime))
					{
						char timestring[20];
						
						// The only time when we will ever get this far when ripstat != B_OK is if
						// we have issues related to misreported track times on an enhanced CD. In this
						// case, we make use of the riptime variable declared above to find out
						// just how much was actually ripped in order to write the proper playing time
						if (ripstat!=B_OK)
							sprintf(timestring,"%.2ld:%.2ld",rippedtime.minutes,rippedtime.seconds);
						else
							sprintf(timestring,"%.2ld:%.2ld",tracktime.minutes,tracktime.seconds);
						node.WriteAttr("Audio:Length",B_STRING_TYPE,0,timestring, strlen(timestring)+1);
					}
				}
				
				// write the file's tags
				BString inString;
				
				syscmd = "tagwriter ";
				inString = gCDData.TrackAt(i);
				inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
				syscmd << "-t " << inString;
				
				inString = gCDData.Artist();
				inString.CharacterEscape("<> '\"\\|?[]{}():;`,",'\\');
				syscmd << " -a " << inString;
				
				if (strlen(gCDData.Genre())>0)
				{
					inString = gCDData.Genre();
					inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
					syscmd << " -g " << inString;
				}
				
				if (strlen(gCDData.Album())>0)
				{
					inString = gCDData.Album();
					inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
					syscmd << " -A " << inString;
				}
				
				syscmd << " -T " << (i+1) << " ";
				syscmd << " -c 'Created by SimplyVorbis' ";
				
				inString = ripname;
				inString.ReplaceAll("/", " - ");
				inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
				syscmd+=inString;
				
				//printf("Tag command: %s\n",syscmd.String());
				system(syscmd.String());
				
				// Move the file to the real destination
				BEntry entry(ripname.String());
#ifdef FAKE_RIPPING
				{
					{
#else
				if (entry.Exists())
				{
					BDirectory destination(destfolder.String());
				
					// overwrite an existing file - allow re-ripping a file :)
					if (entry.MoveTo(&destination,NULL,true)!=B_OK)
					{
#endif
						// chances are that if this failed, it's because the destination
						// path is not on the same volume
						view->Window()->Lock();
						BString out(_T("Copying to "));
						out << destfolder;
						view->fProgressBar->SetText(out.String());
						view->Window()->Unlock();
						
						BString cmddest(destfolder);
						cmddest.CharacterEscape("<> '\"\\|[]{}():;`,",'\\');
						
						// *sigh* Certain characters are not allowed for FAT32 names.
						if (!write_attributes)
						{
							cmddest.RemoveAll("?");
							syscmd="cp -fp ";
							syscmd << inString << " " << cmddest;
						}
						else
						{
							syscmd = "copyattr -d ";
							syscmd << inString << " " << cmddest;
						}
						
						//printf("Copy command: %s\n",syscmd.String());
						if (system(syscmd.String())!=0)
							copyfailed=true;
						
						if (!copyfailed)
						{
							entry.Remove();
							syscmd = "settype -t \"audio/x-vorbis\" ";
							syscmd << cmddest << inString;
							system(syscmd.String());
							printf("type command: %s\n", syscmd.String());
						}
						else
						{
							copyfailed=false;
							showfailalert++;
						}
					}
					BString playlistentry(destfolder.String());
					playlistentry << ripname << "\n";
					playlistfile.Write(playlistentry.String(),playlistentry.Length());
				}
			}
		}
		
		gCDDrive.Stop();

#ifndef FAKE_RIPPING		
		// This will show the alert once in the ripping process, as opposed to after every track.
		if (showfailalert == 1)
		{
			copyfailed=false;
			#ifdef SYS_ZETA
			BAlert *alert = new BAlert("SimplyVorbis",_T("RIpViewMultiline4"),_T("OK"));
			#else
			BAlert *alert = new BAlert("SimplyVorbis","SimplyVorbis ran into unexpected issues copying your "
				"music files to the music folder. They have not been lost, however. After clicking "
				"OK, a window will pop up and you can move them to wherever you want.","OK");
			#endif
			alert->Go();
			
			system("/boot/beos/system/Tracker . &");
		}
#endif

	}
	
	if (make_playlist)
	{
		BNodeInfo nodeinfo(&playlistfile);
		if (nodeinfo.InitCheck()==B_OK)
			nodeinfo.SetType("text/x-playlist");
		playlistfile.Unset();
	}
	
	view->Window()->Lock();
	view->fProgressBar->SetText(_T("Finished."));
	view->Window()->Unlock();
	snooze(1000000);
	
	view->fRipThread = -1;
	view->Window()->PostMessage(M_STOP_ENCODING);
	
	release_sem(abort_thread);
	return 0;
}