Example #1
0
void FileFilter::AddExtension( const String& ext )
{
   String x = ext.Trimmed();
   if ( !x.StartsWith( '.' ) )
      if ( !x.StartsWith( '*' ) )
         x = '*' + x;
   x.ToLowercase(); // case-insensitive file extensions
   if ( !extensions.Contains( x ) )
      extensions.Add( x );
}
Example #2
0
void DatabaseDemo::HandleInput(const String& input)
{
    // Echo input string to stdout
    Print(input);
    row_ = 0;
    if (input == "quit" || input == "exit")
        engine_->Exit();
    else if (input.StartsWith("set") || input.StartsWith("get"))
    {
        // We expect a key/value pair for 'set' command
        Vector<String> tokens = input.Substring(3).Split(' ');
        String setting = tokens.Size() ? tokens[0] : "";
        if (input.StartsWith("set") && tokens.Size() > 1)
        {
            if (setting == "maxrows")
                maxRows_ = Max(ToUInt(tokens[1]), 1U);
            else if (setting == "connstr")
            {
                String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1));
                Database* database = GetSubsystem<Database>();
                DbConnection* newConnection = database->Connect(newConnectionString);
                if (newConnection)
                {
                    database->Disconnect(connection_);
                    connection_ = newConnection;
                }
            }
        }
        if (tokens.Size())
        {
            if (setting == "maxrows")
                Print(ToString("maximum rows is set to %d", maxRows_));
            else if (setting == "connstr")
                Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString()));
            else
                Print(ToString("Unrecognized setting: %s", setting.CString()));
        }
        else
            Print("Missing setting paramater. Recognized settings are: maxrows, connstr");
    }
    else
    {
        // In this sample demo we use the dbCursor event to loop through each row as it is being fetched
        // Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
        //   unless the dbCursor event handler has instructed to filter out the fetched row from the final result
        DbResult result = connection_->Execute(input, true);

        // Number of affected rows is only meaningful for DML statements like insert/update/delete
        if (result.GetNumAffectedRows() != -1)
            Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows()));
    }
    Print(" ");
}
Example #3
0
   String 
   FileUtilities::Combine(const String &path1, const String &path2)
   {
      String firstHalf = path1;
      String secondHalf = path2;

      if (firstHalf.EndsWith(_T("\\")) || firstHalf.EndsWith(_T("/")))
         firstHalf = firstHalf.Mid(0, firstHalf.GetLength() -1);

      if (secondHalf.StartsWith(_T("\\")) || secondHalf.StartsWith(_T("/")))
         secondHalf = secondHalf.Mid(1);

      String result = firstHalf + "\\" + secondHalf;

      return result;
   }
void PlatformAndroid::HandleRefreshAndroidTargetsEvent(StringHash eventType, VariantMap& eventData)
{
    if (eventType == E_SUBPROCESSOUTPUT)
    {
        targetOutput_ += eventData[SubprocessOutput::P_TEXT].GetString();
    }
    else if (eventType == E_SUBPROCESSCOMPLETE)
    {
        refreshAndroidTargetsProcess_ = 0;

        androidTargets_.Clear();

        MemoryBuffer reader(targetOutput_.CString(), targetOutput_.Length() + 1);

        while (!reader.IsEof())
        {
            String line = reader.ReadLine();
            if (line.StartsWith("id:"))
            {
                //id: 33 or "Google Inc.:Google APIs (x86 System Image):19"
                Vector<String> elements = line.Split('\"');
                if (elements.Size() == 2)
                {
                    String api = elements[1];

                    androidTargets_.Push(api);
                }
            }
        }

        SendEvent(E_ANDROIDTARGETSREFRESHED);
    }

}
Example #5
0
FileFormat::FileFormat( const String& nameExtOrMime, bool toRead, bool toWrite ) :
   FileFormatBase()
{
   if ( nameExtOrMime.IsEmpty() )
      throw Error( "FileFormat: Empty format name, file extension or MIME type specified" );

   m_data = new FileFormatPrivate;

   if ( nameExtOrMime.Contains( '/' ) )
   {
      IsoString mimeType( nameExtOrMime );
      m_data->handle = (*API->FileFormat->GetFileFormatByMimeType)( ModuleHandle(), mimeType.c_str(), toRead, toWrite );
      if ( m_data->handle == nullptr )
         throw Error( "FileFormat: No installed image file format was found "
                      "for the specified MIME type \'" + nameExtOrMime + "\' and access conditions" );
   }
   else if ( nameExtOrMime.StartsWith( '.' ) )
   {
      m_data->handle = (*API->FileFormat->GetFileFormatByFileExtension)( ModuleHandle(), nameExtOrMime.c_str(), toRead, toWrite );
      if ( m_data->handle == nullptr )
         throw Error( "FileFormat: No installed image file format was found "
                      "for the specified file extension \'" + nameExtOrMime + "\'and access conditions" );
   }
   else
   {
      IsoString id( nameExtOrMime );
      m_data->handle = (*API->FileFormat->GetFileFormatByName)( ModuleHandle(), id.c_str() );
      if ( m_data->handle == nullptr )
         throw Error( "FileFormat: No installed image file format was found "
                      "with the specified identifier \'" + nameExtOrMime + '\'' );
   }

   m_data->GetCapabilities();
}
Example #6
0
 bool 
 FileUtilities::IsUNCPath(const String &sPath)
 {
    if (sPath.StartsWith(_T("\\\\")))
       return true;
    else
       return false;
 }
long RendererDispatcher::FindURIPrefixInList(const String &requestURI, const ROAnything &uriPrefixList) {
	StartTrace(RendererDispatcher.FindURIPrefixInList);

	long apSz = uriPrefixList.GetSize();
	for (long i = 0; i < apSz; ++i) {
		const char *uriPrefix = uriPrefixList.SlotName(i);
		if (uriPrefix && requestURI.StartsWith(uriPrefix)) {
			return i;
		}
	}
	return -1;
}
Example #8
0
bool Shader::ProcessSource(String& code, Deserializer& source)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // If the source if a non-packaged file, store the timestamp
    File* file = dynamic_cast<File*>(&source);
    if (file && !file->IsPackaged())
    {
        FileSystem* fileSystem = GetSubsystem<FileSystem>();
        String fullName = cache->GetResourceFileName(file->GetName());
        unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
        if (fileTimeStamp > timeStamp_)
            timeStamp_ = fileTimeStamp;
    }
    
    // Store resource dependencies for includes so that we know to reload if any of them changes
    if (source.GetName() != GetName())
        cache->StoreResourceDependency(this, source.GetName());
    
    while (!source.IsEof())
    {
        String line = source.ReadLine();
        
        if (line.StartsWith("#include"))
        {
            String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();
            
            SharedPtr<File> includeFile = cache->GetFile(includeFileName);
            if (!includeFile)
                return false;
            
            // Add the include file into the current code recursively
            if (!ProcessSource(code, *includeFile))
                return false;
        }
        else
        {
            code += line;
            code += "\n";
        }
    }

    // Finally insert an empty line to mark the space between files
    code += "\n";
    
    return true;
}
Example #9
0
   bool
   MailImporter::GetRootLevelDirectory_(const String &fullPath, String &rootLevel)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Takes an input parameter such as C:\DataDir\Account\Sub1\Sub2\Test.eml and
   // returns the root of that hierarcy, such as C:\Datadir\Account in this case.
   //---------------------------------------------------------------------------()
   {
      // The file must be located in the data directory. Make sure this is the case.
      const String dataDirectory = IniFileSettings::Instance()->GetDataDirectory();

      if (!fullPath.StartsWith(dataDirectory))
         return false;

      int currentTrimPosition = dataDirectory.GetLength() + 1;

      const String publicFolderName = IMAPConfiguration::GetPublicFolderDiskName();

      // Is the file located in the public folder?
      if (fullPath.FindNoCase(publicFolderName, currentTrimPosition) == currentTrimPosition)
      {
         // The file is located in the public folder.
         currentTrimPosition += publicFolderName.GetLength() + 1;
      }
      else
      {
         // The file is either located in the queue folder or in an account folder.
         int slashPosition = fullPath.Find(_T("\\"), currentTrimPosition);
         if (slashPosition < 0)
            return false;

         int accountSlashPosition = fullPath.Find(_T("\\"), slashPosition+1);

         if (accountSlashPosition > 0)
         {
            // The file is locate din the queue folder.
            currentTrimPosition = accountSlashPosition+1;
         }
      }

      rootLevel = fullPath.Mid(0, currentTrimPosition);
      return true;
   }
Example #10
0
Vector<String> SvnInfo(const String& package)
{
	Vector<String> info;
	String d = GetFileFolder(PackagePath(package));
	if(IsSvnDir2(d)) {
		String v = Sys("svnversion " + d);
		if(IsDigit(*v))
			info.Add("#define bmSVN_REVISION " + AsCString(TrimBoth(v)));
		v = Sys("svn info " + d);
		StringStream in(v);
		while(!in.IsEof()) {
			String l = in.GetLine();
			if(l.StartsWith("URL: ")) {
				info.Add("#define bmSVN_URL " + AsCString(TrimBoth(l.Mid(5))));
				break;
			}
		}
	}
	return info;
}
Example #11
0
   bool 
   MailImporter::MoveToNamedSubdirectory_(const String &sourceFile, String &resultFile, String &newFullPath)
   {
      // The file must be located in the data directory. Make sure this is the case.
      const String dataDirectory = IniFileSettings::Instance()->GetDataDirectory();

      if (!sourceFile.StartsWith(dataDirectory))
         return false;

      // Create a new file name.
      resultFile = Message::GenerateFileName();

      String guidFolder = resultFile.Mid(1,2);
      
      // The file could be located in an incorrect folder, not following the name standard
      // for sub folders in hMailServer. Retrieve the correct folder name so that we can
      // move the message into the correct location.
      
      String currentCorrectDirectory; 
      if (!GetRootLevelDirectory_(sourceFile, currentCorrectDirectory))
         return false;

      String destinationDirectory = FileUtilities::Combine(currentCorrectDirectory, guidFolder);
      if (!FileUtilities::Exists(destinationDirectory))
         FileUtilities::CreateDirectoryRecursive(destinationDirectory);

      String destinationFile = FileUtilities::Combine(destinationDirectory, resultFile);

      if (FileUtilities::Move(sourceFile, destinationFile))
      {
         newFullPath = destinationFile;
         return true;
      }
      
      return false;
   }
Example #12
0
bool JSVM::ExecuteScript(const String& scriptPath)
{
    String path = scriptPath;
    if (!path.StartsWith("Scripts/"))
        path = "Scripts/" + path;

    if (!path.EndsWith(".js"))
        path += ".js";

    SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));

    if (file.Null())
    {
        return false;
    }

    String source;

    file->ReadText(source);
    source.Append('\n');

    duk_push_string(ctx_, file->GetFullPath().CString());
    if (duk_eval_raw(ctx_, source.CString(), 0,
                     DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
    {
        if (duk_is_object(ctx_, -1))
            SendJSErrorEvent(path);

        duk_pop(ctx_);
        return false;
    }

    duk_pop(ctx_);

    return true;
}
Example #13
0
void MessageManager::ProcessMessage(Message * message)
{
	// Check for UI-messages first.
	String msg = message->msg;
//	UserInterface * globalUI = GlobalUI();
	// Do note that not all messages uses the string-argument...
//	if (!msg.Length())
//		return;

	if (message->recipientEntity)
	{
		message->recipientEntity->ProcessMessage(message);
	}

	// Let active lighting process messages if wanted.
	Lighting * activeLighting = Graphics.ActiveLighting();
	if (activeLighting)
	{
		if (activeLighting->ProcessMessage(message))
			return;
	}
			
	WindowMan.ProcessMessage(message);
	UI::ProcessMessage(message);

	switch(message->type)
	{
		case MessageType::BOOL_MESSAGE:
		{
			BoolMessage * bm = (BoolMessage*) message;
			if (msg == "BGMEnabled")
			{
				QueueAudio(new AMSetb(AT_BGM_ENABLED, bm->value));
			}
			break;
		}
		case MessageType::INTEGER_MESSAGE:
		{
			IntegerMessage * im = (IntegerMessage*) message;
			if (msg == "SetMasterVolume")
			{
				QueueAudio(new AMSet(AT_MASTER_VOLUME, im->value * 0.01f));
			}
			else if (msg == "SetBGMVolume")
			{
				QueueAudio(new AMSet(AT_BGM_VOLUME, im->value * 0.01f));
			}
			else if (msg == "SetSFXVolume")
			{
				QueueAudio(new AMSet(AT_SFX_VOLUME, im->value * 0.01f));
			}
			break;
		}
		case MessageType::COLLISSION_CALLBACK:
		{
			CollisionCallback * cc = (CollisionCallback*) message;
			/// o.o
			Entity * one = cc->one;
			Entity * two = cc->two;
			one->ProcessMessage(cc);
			two->ProcessMessage(cc);
			break;	
		}
		case MessageType::RAYCAST:
		{
			Raycast * raycast = (Raycast*) message;
			if (raycast->relevantEntity)
			{
				raycast->relevantEntity->ProcessMessage(message);
			}
			break;	
		}
		case MessageType::DRAG_AND_DROP:
		{
			DragAndDropMessage * dadm = (DragAndDropMessage*) message;
			// Hover to where the drop is to take place.
			InputMan.MouseMove(HoverWindow(), dadm->position);
			/// Check cursor location, can we drop stuff?
			UIElement * e = InputMan.HoverElement();
			if (e)
				e->ProcessMessage(message);
			break;
		}
		case MessageType::PASTE:
		{
			if (msg.Contains("Paste:"))
			{
				// Check for active ui element.
				UserInterface * ui = ActiveUI();
				if (ui){
					UIElement * element = ui->GetActiveElement();
					if (element)
					{
						element->ProcessMessage(message);
					}
				}
			}	
		}
		case MessageType::STRING:
		{
			msg.SetComparisonMode(String::NOT_CASE_SENSITIVE);
			if (msg.StartsWith("SetLight"))
			{
				Light::ProcessMessageStatic(message);
			}
			else if (msg == "ToggleMute")
			{
				// Mute?
				QueueAudio(new AMGlobal(AM_TOGGLE_MUTE));
			}
			else if (msg.StartsWith("SetGravity"))
			{
				String gravStr = msg.Tokenize("()")[1];
				Vector3f grav;
				grav.ReadFrom(gravStr);
				PhysicsQueue.Add(new PMSet(PT_GRAVITY, grav));
			}
			else if (msg.StartsWith("AdjustMasterVolume("))
			{
				float diff = msg.Tokenize("()")[1].ParseFloat();
				QueueAudio(new AMSet(AT_MASTER_VOLUME, AudioMan.MasterVolume() + diff));
			}
			else if (msg == "CreateEditorCamera")
			{
				CreateEditorCamera();
			}
			else if (msg.Contains("CreateNormalMapTestEntities"))
			{
				// Create some entities.
				Entity * entity = MapMan.CreateEntity("NormalMapSprite", ModelMan.GetModel("sprite.obj"), TexMan.GetTexture("0x77"), Vector3f(0,0,0));
				GraphicsQueue.Add(new GMSetEntityTexture(entity, NORMAL_MAP, "normalMapTest2"));
			}
			if (msg == "AcceptInput:false")
				inputState->acceptInput = false;
			else if (msg.Contains("InputMan.printHoverElement"))
				InputMan.printHoverElement = !InputMan.printHoverElement;
			else if (msg == "SetGlobalState:NULL")
				StateMan.SetGlobalState(NULL);
			else if (msg == "SetActiveState:NULL")
				StateMan.SetActiveState(NULL);
			else if (msg == "StateMan.DeleteStates")
				StateMan.DeleteStates();
			else if (msg == "NetworkMan.Shutdown")
				NetworkMan.Shutdown();
			else if (msg == "StateMan.Shutdown")
				StateMan.shouldLive = false;
			else if (msg == "MultimediaMan.Shutdown")
				MultimediaMan.Shutdown();
			else if (msg == "AudioMan.Shutdown")
				AudioMan.QueueMessage(new AMGlobal(AM_SHUTDOWN));
			else if (msg == "GraphicsMan.Shutdown")
				Graphics.QueueMessage(new GraphicsMessage(GM_SHUTDOWN));
			else if (msg == "PrintScreenshot")
			{
				Graphics.QueueMessage(new GraphicsMessage(GM_PRINT_SCREENSHOT));
			}
			else if (msg.Contains("SetOutOfFocusSleepThread("))
			{
				int sleepTime = msg.Tokenize("()")[1].ParseInt();
				GraphicsMan.QueueMessage(new GMSeti(GM_SET_OUT_OF_FOCUS_SLEEP_TIME, sleepTime));
			}
			else if (msg.StartsWith("RenderGrid"))
			{
				// Disable it, everywhere?
				for (int i = 0; i < WindowMan.GetWindows().Size(); ++i)
				{
					AppWindow * w = WindowMan.GetWindows()[i];
					w->RenderGrid(false);
				}
			}
			else if (msg.Contains("PrintHttpOutput("))
			{
				bool value = msg.Tokenize("()")[1].ParseBool();
				printHttpOutput = value;
			}
			else if (msg.Contains("SetHttpTool:"))
			{
				httpTool = msg.Tokenize(":")[1].ParseInt();
			}
			else if (msg.Contains("HttpGet:"))
			{
				String url = msg - "HttpGet:";
				HttpGet(url);
			}
			else if (msg == "ResumePhysics")
			{
 				PhysicsMan.Resume();
			}
			else if (msg.Contains("PlayBGM:"))
			{
				String source = msg - "PlayBGM:";
				source.RemoveSurroundingWhitespaces();
				AudioMan.QueueMessage(new AMPlayBGM(source, 1.f));
			}
			else if (msg.Contains("NavigateUI(")){
				bool toggle = msg.Tokenize("()")[1].ParseBool();
				InputMan.NavigateUI(toggle);
				return;
			}
			else if (msg == "IgnoreMouseInput")
			{
				bool & ignore = InputMan.ignoreMouse;
				ignore = !ignore;
			}
			else if (msg == "DisableLogging")
			{
				extern bool loggingEnabled;
				loggingEnabled = false;
			}
			else if (msg == "EnableLogging")
			{
				extern bool loggingEnabled;
				loggingEnabled = true;
			}
			else if (msg == "PrintExpressionSymbols")
			{
				Expression::printExpressionSymbols = true;
			}
			else if (msg == "List cameras")
			{
				CameraMan.ListCameras();
			}
			else if (msg == "mute")
			{
				AudioMan.QueueMessage(new AMGlobal(AM_DISABLE_AUDIO));
		//		AudioMan.DisableAudio();
			}
			else if (msg == "muteSFX")
			{
				AudioMan.QueueMessage(new AMGlobal(AM_MUTE_SFX));
			}
			else if (msg == "CreateMainWindow")
			{	
				// Creates the main application AppWindow. A message is sent upon startup from the initializer thread for this.
				if (!WindowMan.MainWindow())
				{
					AppWindow * mainWindow = WindowMan.CreateMainWindow();
					// Optionally set more user-related stuff to the options before creating it.
			
					// Then create it!
					mainWindow->Create();
					/// Create default UI and globalUI that may later on be replaced as needed.
					mainWindow->CreateUI();
					mainWindow->CreateGlobalUI();
					mainWindow->backgroundColor = Vector4f(1,0,0,1);
				}
				// Reveal the main AppWindow to the user now that all managers are allocated.
				WindowMan.MainWindow()->Show();
			}
			else if (msg == "HideWindows")
			{
				if (MainWindow())
				{
					MainWindow()->Hide();
				}
			}
			else if (msg == "DestroyMainWindow" || 
				msg == "DeleteWindows" || 
				msg == "DeleteMainWindow")
			{
				if (WindowMan.MainWindow())
				{
					AppWindow * mainWindow = WindowMan.MainWindow();
					mainWindow->Hide();
					mainWindow->Destroy();
				}
			}
			else if (msg.Contains("MaximizeWindow("))
			{
				String windowName = msg.Tokenize("()")[1];
				AppWindow * window = WindowMan.GetWindowByName(windowName);
				if (window)
				{
					if (!window->IsFullScreen())
						window->ToggleFullScreen();
				}
			}
			else if (msg.Contains("INTERPRET_CONSOLE_COMMAND(this)"))
			{
				String command = message->element->text;
				Message * newMes = new Message(MessageType::CONSOLE_COMMAND);
				newMes->msg = command;
				MesMan.QueueMessage(newMes);	
				return;
			}
			else if (msg == "TogglePause(this)"){
				UIElement * e = message->element;
				if (e->type != UIType::VIDEO)
					return;
				UIVideo * video = (UIVideo*) e;
				video->TogglePause();

			}
			else if (msg.Contains("UIProceed("))
			{
				String name = msg.Tokenize("()")[1];
				UserInterface * ui = RelevantUI();
				UIElement * e = ui->GetElementByName(name);
				if (!e)
					return;
				e->Proceed();
				return;
			}
			else if (msg.Contains("UITextureInput("))
			{
				String name = msg.Tokenize("()")[1];
				UserInterface * ui = RelevantUI();
				UIElement * e = ui->GetElementByName(name);
				if (e->type != UIType::TEXTURE_INPUT)
					return;
				UITextureInput * ti = (UITextureInput*) e;
				TextureMessage * m = new TextureMessage(ti->action, ti->GetTextureSource());
				MesMan.QueueMessage(m);
				return;	
			}
			else if (msg.Contains("UIStringInput("))
			{
				/// Obsolete?
				/*
				String name = msg.Tokenize("()")[1];
				UserInterface * ui = RelevantUI();
				if (!ui)
					return;
				UIElement * e = ui->GetElementByName(name);
				if (e->type != UIType::STRING_INPUT)
					return;
				UIStringInput * si = (UIStringInput*)e;
				SetStringMessage * m = new SetStringMessage(si->action, si->GetValue());
				MesMan.QueueMessage(m);
				*/
				return;
			}
			else if (msg.Contains("UIFloatInput("))
			{
				String name = msg.Tokenize("()")[1];
				UserInterface * ui = RelevantUI();
				UIElement * e = ui->GetElementByName(name);
				if (e->type != UIType::FLOAT_INPUT)
					return;
				UIFloatInput * fi = (UIFloatInput*)e;
				FloatMessage * m = new FloatMessage(fi->action, fi->GetValue());
				MesMan.QueueMessage(m);
				return;
			}
			else if (msg.Contains("UIIntegerInput("))
			{
				String name = msg.Tokenize("()")[1];
				UserInterface * ui = RelevantUI();
				UIElement * e = ui->GetElementByName(name);
				if (e->type != UIType::INTEGER_INPUT)
					return;
				UIIntegerInput * ii = (UIIntegerInput*)e;
				IntegerMessage * m = new IntegerMessage(ii->action, ii->GetValue());
				MesMan.QueueMessage(m);
				return;
			}
			else if (msg.Contains("UIVectorInput("))
			{
				String name = msg.Tokenize("()")[1];
				UserInterface * ui = RelevantUI();
				UIElement * e = ui->GetElementByName(name);
				if (e->type != UIType::VECTOR_INPUT)
					return;
				UIVectorInput * vi = (UIVectorInput*)e;
				/// Fetch vector data from the input first.
				VectorMessage * m = NULL;
				switch(vi->numInputs)
				{
					case 2:
						m = new VectorMessage(vi->action, vi->GetValue2i());
						break;
					case 3:
						m = new VectorMessage(vi->action, vi->GetValue3f());
						break;
					case 4:
						m = new VectorMessage(vi->action, vi->GetValue4f());
						break;
					default:
						assert(false && "implement");
						break;
				}
				if (m)
					MesMan.QueueMessage(m);
				return;
			}
			else if (msg.Contains("setVisibility"))
			{
				List<String> params = msg.Tokenize("(),");
				assert(params.Size() >= 2 && "Invalid amount of arguments to SetVisibility UI command!");

				String uiName = params[1];
				/// Check if the name-parameter is 'this'
				if (uiName == "this"){
					// std::cout<<"\nElement with 'this' lacking name.. fix yo.";
					uiName = message->element->name;
				}
				bool visibility = params[2].ParseBool();
				Graphics.QueueMessage(new GMSetUIb(uiName, GMUI::VISIBILITY, visibility));
				return;
			}
			else if (msg.Contains("SetText(")){
				List<String> params = msg.Tokenize("(),");
				assert(params.Size() >= 2 && "Invalid amount of arguments to SetVisibility UI command!");

				String uiName = params[1];
				/// Check if the name-parameter is 'this'
				if (uiName == "this"){
					// std::cout<<"\nElement with 'this' lacking name.. fix yo.";
					uiName = message->element->name;
				}
				String text = params[2];
				text.Remove("\"", true);
				Graphics.QueueMessage(new GMSetUIs(uiName, GMUI::TEXT, text));
				return;
			}
			else if (msg.Contains("CyclicUIY(")){
				InputMan.cyclicY = msg.Tokenize("()")[1].ParseBool();
				return;
			}
			else if (msg.Contains("Query(")){
				// Create a new UI to place on top of it all!
				String uiName = msg;
				List<String> params = msg.Tokenize("(),");
				assert(params.Size() >= 2);
				String action = params[1];
				/// Create the dialogue
				UIQueryDialogue * dialog = new UIQueryDialogue(action, action);
				dialog->navigateUIOnPush = true;
				dialog->exitable = true;
				if (params.Size() >= 4){
					dialog->headerText = params[2];
					dialog->textToPresent = params[3];
				}
				dialog->CreateChildren();
				/// Add the dialogue to the global UI
				Graphics.QueueMessage(new GMAddGlobalUI(dialog, "root"));
				/// Push it to the top... should not be needed with the global ui.
				Graphics.QueueMessage(GMPushUI::ToUI(dialog, GlobalUI()));
				return;
			}
			else if (msg.Contains("SetFileBrowserDirectory("))
			{
				List<String> params = msg.Tokenize(",()");
				String uiName = params[1];
				UIElement * ui = RelevantUI()->GetElementByName(uiName);
				if (!ui)
					return;
				assert(ui->type == UIType::FILE_BROWSER);
				UIFileBrowser * fb = (UIFileBrowser*)ui;
				String path = params[2];
				if (path == "this")
					path = message->element->text;
				fb->SetPath(path, false);
				return;
			}
			else if (msg.Contains("UpdateFileBrowserDirectory("))
			{
				List<String> params = msg.Tokenize(",()");
				String uiName = params[1];
				UIElement * ui = RelevantUI()->GetElementByName(uiName);
				if (!ui)
					return;
				assert(ui->type == UIType::FILE_BROWSER);
				UIFileBrowser * fb = (UIFileBrowser*)ui;
				String path = params[2];
				if (path == "this")
					path = message->element->text;
				fb->UpdatePath(path, false);
				return;
			}
			else if (msg.Contains("EvaluateFileBrowserSelection("))
			{
				List<String> params = msg.Tokenize("()");
				String uiName = params[1];
				UIElement * ui = RelevantUI()->GetElementByName(uiName);
				if (!ui)
					return;
				FileEvent * message = new FileEvent();
				UIFileBrowser * fb = (UIFileBrowser*)ui;
				message->msg = fb->action;
				message->files = fb->GetFileSelection();
				// Queue the new message.
				QueueMessage(message);
				return;
			}
			else if (msg.Contains("SetFileBrowserFile("))
			{
				List<String> params = msg.Tokenize(",()");
				String uiName = params[1];
				UIElement * ui = RelevantUI()->GetElementByName(uiName);
				if (!ui)
					return;
				assert(ui->type == UIType::FILE_BROWSER);
				UIFileBrowser * fb = (UIFileBrowser*)ui;
				String file = params[2];
				if (file == "this"){
					file = message->element->text;
				}
				fb->SetActiveFile(file);
				return;
			}
			else if (msg.Contains("OpenFileBrowser(")){
				/// Parse stuff
				List<String> params = msg.Tokenize("(),");
				assert(params.Size() >= 3);
				String title = params[1];
				title.Remove("\"", true);
				String action = params[2];
				String filter;
				if (params.Size() >= 4){
					filter = params[3];
					filter.Remove("\"", true);
				}
				/// Create the browser.
				UIFileBrowser * fileBrowser = new UIFileBrowser(title, action, filter);
				fileBrowser->CreateChildren();
				fileBrowser->LoadDirectory(false);
				/// Push it to the UI.
				UserInterface * ui = RelevantUI();
				assert(ui);
				Graphics.QueueMessage(new GMAddUI(fileBrowser, "root", ui));
				Graphics.QueueMessage(GMPushUI::ToUI(fileBrowser, ui));
				return;
			}
			else if (msg.Contains("QuitApplication"))
			{
				StateMan.QueueState(StateMan.GetStateByID(GameStateID::GAME_STATE_EXIT));
				return;
			}
			else if (msg.Contains("PushToStack(") || msg.Contains("PushUI(")){
				// Fetch target.
				List<String> params = msg.Tokenize("(),");
				assert(params.Size() >= 2 && "Invalid amount of arguments to PushToStack UI command!");
				if (params.Size() < 2)
				{
					LogMain("Bad arguments in message: "+msg, ERROR);
					return;
				}
				PushUI(params[1]);
				return;
			}
			else if (msg.Contains("PopFromStack(") || msg.Contains("PopUI("))
			{
//				std::cout<<"\nPopFromStack/PopUI received.";
				// Fetch target.
				List<String> params = msg.Tokenize("(),");
				assert(params.Size() >= 2 && "Invalid amount of arguments to PopFromStack UI command!");
				if (params.Size() < 2){
					std::cout<<"\nToo few parameters.";
					return;
				}
				String uiName = params[1];
				if (uiName == "this")
					uiName = message->element->name;
				PopUI(uiName);
				return;
			}
			else if (msg == "Back")
			{
				UserInterface * ui = RelevantUI();
				UIElement * stackTop = ui->GetStackTop();
				Graphics.QueueMessage(new GMPopUI(stackTop->name, ui));
				return;
			}
			else if (msg.Contains("begin_input(") ||
				msg.Contains("BeginInput("))
			{
				String elementName = msg.Tokenize("()")[1];
				UIElement * element;
				if (elementName == "this")
					element = message->element;
				else
					element = StateMan.ActiveState()->GetUI()->GetElementByName(elementName);
				if (!element)
					return;
				assert(element->demandInputFocus);
				((UIInput*)element)->BeginInput();
				return;
				/*
				UserInterface * ui = StateMan.ActiveState()->GetUI();
				UIElement * element = message->element;
				if (!element){
					std::cout<<"\nNo active element, fetching hover element.";
					element = ui->GetHoverElement();
				}
				if (element != NULL){
					// assert(element->onTrigger);
					if (!element->onTrigger)
						std::cout<<"\nBegnning input for element without onTrigger specified!";
					InputMan.SetActiveUIInputElement(element);
					InputMan.EnterTextInputMode(element->onTrigger);
				}
				else
					assert(false && "NULL-element :<");
				return;
				*/
			}
			else if (msg.Contains("Remove(") || msg.Contains("DeleteUI("))
			{
				UserInterface * ui = StateMan.ActiveState()->GetUI();
				UIElement * element;
				String uiName = msg.Tokenize("()")[1];
				/// this-deletion
				if (uiName == "this"){
					if (message->element)
						element = message->element;
					else
						element = ui->GetActiveElement();
				}
				/// Named deletion
				else {
					element = ui->GetElementByName(uiName);
				}
				/// For all usual AI, the state is not active after activation, so just grab the one with the hover-state!
				if (element == NULL)
					element = ui->GetHoverElement();
				assert(element);
				if (element == NULL){
					std::cout<<"\nERRORRRR: Invalid hellelemend? No active hover element, yo..";
					return;
				}
				Graphics.QueueMessage(new GMRemoveUI(element));
				return;
			}
			else if (msg.Contains("ContinueEvent(")){
				List<Script*> events, mapEvents;
				Map * map = MapMan.ActiveMap();
				if (map)
					mapEvents = map->GetEvents();
				List<Script*> moreEvents = ScriptMan.GetActiveEvents();
				events += mapEvents + moreEvents;
				String targetEvent = msg.Tokenize("()")[1];
				for (int i = 0; i < events.Size(); ++i){
					Script * event = events[i];
					if (event->name == targetEvent)
						event->lineFinished = true;
				}
				return;
			}
			else if (msg.Contains("ActivateDialogueAlternative(")){
				List<Script*> events = MapMan.ActiveMap()->GetEvents();
				List<Script*> moreEvents = ScriptMan.GetActiveEvents();
				events += moreEvents;
				String argsString = msg.Tokenize("()")[1];
				List<String> args = argsString.Tokenize(" ,");
				String targetEvent = args[0];
				String alternative = args[1];
				assert(alternative);
				for (int i = 0; i < events.Size(); ++i){
					Script * e = events[i];
					if (e->name == targetEvent){
						e->ContinueToAlternative(alternative);
					}
				}
				return;
			}

			break;
		}
	}

	
	// First send it to global state
	StateManager * stateMan = StateManager::Instance();
	if (stateMan)
	{
		AppState * global = StateMan.GlobalState();
		if (global)
			global->ProcessMessage(message);
		// Send it to the state for processing
		if (StateMan.ActiveState())
			StateMan.ActiveState()->ProcessMessage(message);
	}
}
Example #14
0
bool HttpsClient::ProxyConnect()
{
	if(use_proxy) {
		int start_time = msecs();
		int end_time = msecs() + timeout_msecs;
		while(!socket.PeekWrite(1000)) {
			int time = msecs();
			if(time >= end_time) {
				error = NFormat(t_("%s:%d: connecting to host timed out"), socket_host, socket_port);
				Close();
				return false;
			}
		}
		String host_port = host;
		if(port)
			host_port << ':' << port;
		else
			host_port << ":443";
		String request;
		request << "CONNECT " << host_port << " HTTP/1.1\r\n"
		        << "Host: " << host_port << "\r\n";
		if(!IsNull(proxy_username))
			request << "Proxy-Authorization: Basic "
			        << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n";
		request << "\r\n";
		LLOG(request);
		int written = 0;
		while(msecs() - end_time < 0) {
			int nwrite = socket.WriteWait(request.GetIter(written), min(request.GetLength() - written, 1000), 1000);
			if(socket.IsError()) {
				error = Socket::GetErrorText();
				Close();
				return false;
			}
			if((written += nwrite) >= request.GetLength())
				break;
		}
		if(written < request.GetLength()) {
			error = NFormat(t_("%s:%d: timed out sending request to server"), host, port);
			Close();
			return false;
		}
		String line = ReadUntilProgress('\n', start_time, end_time, false);
		LLOG("P< " << line);
		if(socket.IsError()) {
			error = Socket::GetErrorText();
			Close();
			return false;
		}
		if(!line.StartsWith("HTTP") || line.Find(" 2") < 0) {
			error = "Invalid proxy reply: " + line;
			Close();
			return false;
		}
		while(line.GetCount()) {
			line = ReadUntilProgress('\n', start_time, end_time, false);
			if(*line.Last() == '\r')
				line.Trim(line.GetCount() - 1);
			LLOG("P< " << line << " len " << line.GetCount());
			if(socket.IsError()) {
				error = Socket::GetErrorText();
				Close();
				return false;
			}
		}
		use_proxy = false;
		while(!socket.PeekWrite(1000)) {
			int time = msecs();
			if(time >= end_time) {
				error = NFormat(t_("%s:%d: connecting to host timed out"), socket_host, socket_port);
				Close();
				return false;
			}
		}
	}
	return true;
}
Example #15
0
    void IPCPlayerApp::ProcessArguments()
    {
        PlayerApp::ProcessArguments();

        FileSystem* fileSystem = GetSubsystem<FileSystem>();

        if (!fileSystem)
        {
            ErrorExit("IPCPlayerApp::ProcessArguments FileSystem subsystem does not exist");
        }

        String resourcePrefix;
        engineParameters_["ResourcePrefixPaths"] = "";

        for (unsigned i = 0; i < arguments_.Size(); ++i)
        {
            if (arguments_[i].Length() > 1)
            {
                String argument = arguments_[i].ToLower();
                String value = i + 1 < arguments_.Size() ? arguments_[i + 1] : String::EMPTY;

                if (argument.StartsWith("--ipc-server=") || argument.StartsWith("--ipc-client="))
                {
                    subprocess_ = true;
                }
                else if (argument == "--debug")
                {
                    debugPlayer_ = true;
                }
                else if (argument == "--resourceprefix" && value.Length())
                {
                    resourcePrefix = value;
                    engineParameters_["ResourcePrefixPaths"] = resourcePrefix;
                }
                else if (argument == "--project" && value.Length())
                {
                    value = AddTrailingSlash(value);

                    AddEngineConfigSearchPath(value + "Settings/");

                    // check that cache exists
                    if (!fileSystem->DirExists(value + "Cache"))
                    {
                        ErrorExit("Project cache folder does not exist, projects must be loaded into the Atomic Editor at least once before using the --player command line mode");
                        return;
                    }

#ifdef ATOMIC_DEV_BUILD

                    String resourcePaths = ToString("%s/Resources/CoreData;%s/Resources/PlayerData;%sResources;%s;%sCache",
                        ATOMIC_ROOT_SOURCE_DIR, ATOMIC_ROOT_SOURCE_DIR, value.CString(), value.CString(), value.CString());

#else

#ifdef __APPLE__
                    if (!resourcePrefix.Length())
                    {
                        engineParameters_["ResourcePrefixPaths"] = fileSystem->GetProgramDir() + "../Resources";
                    }
#else
                    if (!resourcePrefix.Length())
                    {
                        engineParameters_["ResourcePrefixPaths"] = fileSystem->GetProgramDir() + "Resources";
                    }

#endif

                    String resourcePaths = ToString("CoreData;PlayerData;%s/;%s/Resources;%s;%sCache",
                        value.CString(), value.CString(), value.CString(), value.CString());
#endif

                    ATOMIC_LOGINFOF("Adding ResourcePaths: %s", resourcePaths.CString());

                    engineParameters_["ResourcePaths"] = resourcePaths;

                }
            }
        }

        // IPC client player should not auto exit if a subprocess
        if (subprocess_)
            engine_->SetAutoExit(false);

    }
Example #16
0
status_t ExpandFilePathWildCards(const String & path, Queue<String> & outputPaths, bool isSimpleFormat)
{
   const char * fs = GetFilePathSeparator();
   if (path.StartsWith(fs)) return ExpandFilePathWildCardsAux(fs,  path()+1, outputPaths, isSimpleFormat);  // start at root
                       else return ExpandFilePathWildCardsAux(".", path,     outputPaths, isSimpleFormat);  // start at current folder
}
// Parses a string that the user typed in to stdin and creates a Message to send to the server.
static MessageRef ParseStdinCommand(const String & stdinCommand)
{
   if (stdinCommand.IsEmpty()) return MessageRef();

   StringTokenizer tok(stdinCommand(), " ");
   const String cmd  = tok();
   if ((cmd == "set") || (cmd == "s"))
   {
      const String theRest = String(tok.GetRemainderOfString());
      if (theRest.HasChars())
      {
         const int eqIdx = theRest.IndexOf('=');
         const String pathArg = (eqIdx >= 0) ? theRest.Substring(0, eqIdx).Trim() : theRest;
         const String dataArg = (eqIdx >= 0) ? theRest.Substring(eqIdx+1).Trim()  : "default";

         if (pathArg.StartsWith("/"))
         {
            LogTime(MUSCLE_LOG_ERROR, "PR_COMMAND_SETDATA paths cannot start with a slash (because you're only allowed to set nodes within your own session-folder!)\n");
         }
         else
         {
            LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_SETDATA to set node at subpath [%s] to contain a Message containing data string [%s]\n", pathArg(), dataArg());
            if (HasRegexTokens(pathArg)) LogTime(MUSCLE_LOG_WARNING, "Note: PR_COMMAND_SETDATA won't do pattern-matching on wildcard chars; rather they will become literal chars in the node-path!\n");

             MessageRef dataPayloadMsg = GetMessageFromPool();
             dataPayloadMsg()->AddString("User String", dataArg);

             MessageRef setDataMsg = GetMessageFromPool(PR_COMMAND_SETDATA);
             setDataMsg()->AddMessage(pathArg, dataPayloadMsg);

             return setDataMsg;
         }
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  set my_node_dir/my_node_file = some text to put in the node\n");
   }
   else if ((cmd == "get") || (cmd == "g"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_GETDATA to do a one-time download of nodes matching the following path: [%s]\n", pathArg());

         MessageRef getDataMsg = GetMessageFromPool(PR_COMMAND_GETDATA);
         getDataMsg()->AddString(PR_NAME_KEYS, pathArg);
         return getDataMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  get /*/*\n");
   }
   else if ((cmd == "delete") || (cmd == "d"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_REMOVEDATA to delete any nodes matching the following path: [%s]\n", pathArg());

         MessageRef deleteNodesMsg = GetMessageFromPool(PR_COMMAND_REMOVEDATA);
         deleteNodesMsg()->AddString(PR_NAME_KEYS, pathArg);
         return deleteNodesMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  delete *\n");
   }
   else if ((cmd == "subscribe") || (cmd == "S"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_SETPARAMETERS to set up a \"live\" subscription to any nodes matching the following path: [%s]\n", pathArg());

         MessageRef subscribeToNodesMsg = GetMessageFromPool(PR_COMMAND_SETPARAMETERS);
         subscribeToNodesMsg()->AddBool(String("SUBSCRIBE:%1").Arg(pathArg), true);
         return subscribeToNodesMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  subscribe /*/*\n");
   }
   else if ((cmd == "unsubscribe") || (cmd == "u"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_REMOVEPARAMETERS to get rid of any \"live\" subscriptions that match the following string: [SUBSCRIBE:%s]\n", pathArg());

         MessageRef unsubscribeFromNodesMsg = GetMessageFromPool(PR_COMMAND_REMOVEPARAMETERS);
         unsubscribeFromNodesMsg()->AddString(PR_NAME_KEYS, String("SUBSCRIBE:%1").Arg(pathArg));
         return unsubscribeFromNodesMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  unsubscribe /*/*\n");
   }
   else if ((cmd == "msg") || (cmd == "m"))
   {
      const String pathArg  = tok();
      if (pathArg.HasChars())
      {
         const String userText = tok.GetRemainderOfString();

         MessageRef chatMsg = GetMessageFromPool(1234);  // any non-PR_COMMAND_* message code will work here
         chatMsg()->AddString(PR_NAME_KEYS, pathArg);
         chatMsg()->AddString("chat_text", userText);
         return chatMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  msg /*/* Hey guys!\n");
   }
   else if ((cmd == "help") || (cmd == "h"))
   {
      PrintHelp();
   }
   else LogTime(MUSCLE_LOG_ERROR, "Couldn't parse stdin command [%s].  Enter help to review the command-help-text.\n", stdinCommand());

   return MessageRef();  // nothing to send for now
}
Example #18
0
// Parses TOC and fills tocTree control
bool HelpViewer::LoadTOC(String const &tocLink)
{
	// TOC is composed by QTF lines with a TOC link and label text
	// lines not containing the TOC link are simply ignored
	// TOC level is represented by number of TABS contained
	// inside a line; zero tabs means toplevel, id 0 of tocTree
	Vector<int>ids;
	ids.Add(0);
	int curLevel = 0;
	int curId = 0;
	TreeCtrl tocTree;
	
	Topic t = GetTopic(tocLink);
	if(IsNull(t.text))
		return false;

	String label = t.label;
	String topic = t.link;

	// sets toc root string from topic ticle
	tocTree.SetRoot(Null, t.title);
	
	// converts QTF to RichTxt, easier to analyze
	RichText txt = ParseQTF(t.text);

	// extract all paragraphs from RichTxt, skip other objects
	for(int iPart = 0; iPart < txt.GetPartCount(); iPart++)
	{
		String tocLine;
		String lineLink;
		if(!txt.IsPara(iPart))
			continue;
		RichPara p = txt.Get(iPart);
		for(int iParaPart = 0; iParaPart < p.GetCount(); iParaPart++)
		{
			RichPara::Part &paraPart = p.part[iParaPart];
			if(paraPart.format.link != "")
				lineLink = paraPart.format.link;
			if(paraPart.NonText())
				continue;
			tocLine += paraPart.text.ToString();
		}
		// if part contains no text nor link to topic stuffs, simply skip it
		if(tocLine == "" || lineLink == "" || !lineLink.StartsWith("topic:"))
			continue;
		
		// now we should count tabls to get TOC indent level
		int level = 0;
		int j;
		while( (j = tocLine.Find(0x09)) >= 0)
		{
			level++;
			tocLine.Remove(j);
		}
		// allows just SINGLE UPPER level change, i.e., deeper ONE level from current
		// for each step; backleveling is possible at any depth
		if(level > curLevel+1)
			return false;
		if(level > curLevel)
		{
			ids.Add(curId);
			curLevel++;
		}
		else while(curLevel > level)
		{
			curLevel--;
			ids.Pop();
		}

		// add the line to correct tree node
		curId = tocTree.Add(ids.Top(), Null, Value(lineLink), Value(tocLine));
	}
	
	// if the tree control is non empty, appends it to the main TOC TreeCtrl
	if(tocTree.GetChildCount(0))
		AppendTOC(tocTree);

	
	// opens all content tree and display first item
	mainTocTree.OpenDeep(0);
	mainTocTree.SetCursor(2);

	// stores first topic at top of stack
	String curLink = mainTocTree.Get();
	stack.Clear();
	stack.Add(curLink);
	tos = 0;
	
	return true;
}
BonkEnc::InputFilter *BonkEnc::Utilities::CreateInputFilter(const String &iFile, Track *trackInfo)
{
	Array<String>	 extensions;
	Array<Int>	 indexes;

	String		 file = iFile.ToLower();

	for (Int i = 0; i < DLLInterfaces::winamp_in_plugins.Length(); i++)
	{
		Int	 n = 1;
		Int	 k = 0;
		String	 extension;

		for (Int j = 0; true; j++)
		{
			if (!(n & 1))
			{
				if (DLLInterfaces::winamp_in_modules.GetNth(i)->FileExtensions[j] == 0) n++;
			}
			else
			{
				extension[k++] = DLLInterfaces::winamp_in_modules.GetNth(i)->FileExtensions[j];

				if (DLLInterfaces::winamp_in_modules.GetNth(i)->FileExtensions[j] == 0)
				{
					String	 extension2 = extension;
					Int	 o = 0;		

					for (Int m = 0; m <= extension2.Length(); m++)
					{
						if (extension2[m] == ';' || extension2[m] == 0)
						{
							extension[m - o] = 0;

							extensions.Add(extension);
							indexes.Add(i);

							o = m + 1;
						}
						else
						{
							extension[m - o] = tolower(extension2[m]);
						}
					}

					k = 0;
					n++;
					extension = "";
				}
			}

			if (DLLInterfaces::winamp_in_modules.GetNth(i)->FileExtensions[j] == 0 && DLLInterfaces::winamp_in_modules.GetNth(i)->FileExtensions[j + 1] == 0) break;
		}
	}

	Int	 found = -1;

	for (Int j = 0; j < extensions.Length(); j++)
	{
		if (file.EndsWith(extensions.GetNth(j)))
		{
			found = j;

			break;
		}
	}

	InputFilter	*filter_in = NIL;

	if ((file.StartsWith("/cda") || file.EndsWith(".cda")) && BonkEnc::currentConfig->enable_cdrip && BonkEnc::currentConfig->cdrip_numdrives >= 1)
	{
		filter_in = new FilterInCDRip(BonkEnc::currentConfig, trackInfo);
	}
	else if ((file.EndsWith(".mp1") || file.EndsWith(".mp2") || file.EndsWith(".mp3")) && BonkEnc::currentConfig->enable_mad)
	{
		filter_in = new FilterInMAD(BonkEnc::currentConfig, trackInfo);
	}
	else if ((file.EndsWith(".mp4") || file.EndsWith(".m4a") || file.EndsWith(".m4b")) && BonkEnc::currentConfig->enable_mp4 && BonkEnc::currentConfig->enable_faad2)
	{
		filter_in = new FilterInMP4(BonkEnc::currentConfig, trackInfo);
	}
	else if (file.EndsWith(".ogg") && BonkEnc::currentConfig->enable_vorbis)
	{
		filter_in = new FilterInVORBIS(BonkEnc::currentConfig, trackInfo);
	}
	else if (file.EndsWith(".aac") && BonkEnc::currentConfig->enable_faad2)
	{
		filter_in = new FilterInFAAD2(BonkEnc::currentConfig, trackInfo);
	}
	else if (file.EndsWith(".bonk") && BonkEnc::currentConfig->enable_bonk)
	{
		filter_in = new FilterInBONK(BonkEnc::currentConfig, trackInfo);
	}
	else if (file.EndsWith(".flac") && BonkEnc::currentConfig->enable_flac)
	{
		filter_in = new FilterInFLAC(BonkEnc::currentConfig, trackInfo);
	}
	else if (file.EndsWith(".wma") && BonkEnc::currentConfig->enable_wma)
	{
		filter_in = new FilterInWMA(BonkEnc::currentConfig, trackInfo);
	}
	else if (found != -1)
	{
		filter_in = new FilterInWinamp(BonkEnc::currentConfig, trackInfo, DLLInterfaces::winamp_in_modules.GetNth(indexes.GetNth(found)));
	}
	else
	{
		InStream	*f_in = new InStream(STREAM_FILE, file, IS_READONLY);
		Int		 magic = f_in->InputNumber(4);

		delete f_in;

		switch (magic)
		{
			case 1297239878:
				filter_in = new FilterInAIFF(BonkEnc::currentConfig, trackInfo);
				break;
			case 1684960046:
				filter_in = new FilterInAU(BonkEnc::currentConfig, trackInfo);
				break;
			case 1634038339:
				filter_in = new FilterInVOC(BonkEnc::currentConfig, trackInfo);
				break;
			case 1179011410:
				filter_in = new FilterInWAVE(BonkEnc::currentConfig, trackInfo);
				break;
		}
	}

	return filter_in;
}
Example #20
0
static status_t ExpandFilePathWildCardsAux(const String & curDir, const String & path, Queue<String> & outputPaths, bool isSimpleFormat)
{
   const char * fs = GetFilePathSeparator();
   const int32 sepIdx = path.IndexOf(fs);
   const String firstClause  = (sepIdx >= 0) ? path.Substring(0, sepIdx) : path;
   const String restOfString = (sepIdx >= 0) ? path.Substring(sepIdx+1) : GetEmptyString();

   StringMatcher sm(firstClause, isSimpleFormat);
   Directory dir(curDir());
   if (dir.IsValid())
   {
      if (CanWildcardStringMatchMultipleValues(firstClause))
      {
         while(1)
         {
            const char * fn = dir.GetCurrentFileName();
            if (fn)
            {
               if ((strcmp(fn, ".") != 0)&&(strcmp(fn, "..") != 0)&&((fn[0] != '.')||(firstClause.StartsWith(".")))&&(sm.Match(fn)))
               {
                  const String childPath = String(dir.GetPath())+fn;
                  if (restOfString.HasChars())
                  {
                     if (ExpandFilePathWildCardsAux(childPath, restOfString, outputPaths, isSimpleFormat) != B_NO_ERROR) return B_ERROR;
                  }
                  else if (outputPaths.AddTail(childPath) != B_NO_ERROR) return B_ERROR;
               } 
               dir++;
            }
            else break;
         }
      }
      else
      {
         const String childPath = String(dir.GetPath())+firstClause;
         if (FilePathInfo(childPath()).Exists())
         {
            if (restOfString.HasChars())
            {
               if (ExpandFilePathWildCardsAux(childPath, restOfString, outputPaths, isSimpleFormat) != B_NO_ERROR) return B_ERROR;
            }
            else if (outputPaths.AddTail(childPath) != B_NO_ERROR) return B_ERROR;
         }
      }
   }
   return B_NO_ERROR;
}