bool ModelImporter::Import()
{
    String modelAssetFilename = asset_->GetPath();

    importNode_ = new Node(context_);

    // skip external animations, they will be brought in when importing their
    // corresponding model
    if (!modelAssetFilename.Contains("@"))
    {
        ImportModel();

        if (importAnimations_)
        {
            ImportAnimations();
        }

    }

    File outFile(context_);

    if (!outFile.Open(asset_->GetCachePath(), FILE_WRITE))
        ErrorExit("Could not open output file " + asset_->GetCachePath());

    importNode_->SaveXML(outFile);

    importNode_ = 0;

    return true;
}
Example #2
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 #3
0
/// Default processor to react to messages created by the default bindings declared above.
void ProcessCameraMessages(String msg, Camera * forCamera)
{
	if (!forCamera->inputFocus)
		return;
	if (msg == "ResetCamera")
	{
		forCamera->Reset();		
	}
	else if (msg == "CamIncreaseSpeed")
	{
		forCamera->flySpeed = ClampedFloat(forCamera->flySpeed * 1.1f + 0.1f, 0.1f, 100.f);
	}
	else if (msg == "CamDecreaseSpeed")
	{
		forCamera->flySpeed = ClampedFloat(forCamera->flySpeed * 0.9f - 0.1f, 0.1f, 100.f);
	}
	else if (msg.Contains("StartCameraRot"))
	{
		String dirStr = msg - "StartCameraRot";
		int direction = Direction::Get(dirStr);
		forCamera->BeginRotate(direction);	
	}
	else if (msg.Contains("StopCameraRot"))
	{
		String dirStr = msg - "StopCameraRot";
		int direction = Direction::Get(dirStr);
		forCamera->EndRotate(direction);	
	}
	else if (msg.Contains("StartCamera"))
	{
		String dirStr = msg - "StartCamera";
		int direction = Direction::Get(dirStr);
		forCamera->Begin(direction);
	}
	else if (msg.Contains("StopCamera"))
	{
		String dirStr = msg - "StopCamera";
		int direction = Direction::Get(dirStr);
		forCamera->End(direction);
	}
}
Example #4
0
/// Yus.
bool Mesh::SaveObj(String path)
{
	if (!path.Contains(".obj"))
		path = path + ".obj";
	File objFile(path);
	bool ok = objFile.OpenForWritingText();
	if (!ok)
		return false;
	std::fstream & fstream = objFile.GetStream();
	fstream<<"o "<<name;
	for (int i = 0; i < vertices.Size(); ++i)
	{
		Vector3f & v = vertices[i];
		fstream<<"\nv "<<v;
	}
	for (int i = 0; i < uvs.Size(); ++i)
	{
		Vector2f & uv = uvs[i];
		fstream<<"\nvt "<<uv;
	}
	for (int i = 0; i < normals.Size(); ++i)
	{
		Vector3f & n = normals[i];
		fstream<<"\nvn "<<n;
	}
	for (int i = 0; i < faces.Size(); ++i)
	{
		MeshFace & f = faces[i];
		fstream<<"\nf";
		for (int i = 0; i < f.vertices.Size(); ++i)
		{
			fstream<<" "<<(f.vertices[i]+1);
			if (f.normals.Size() || f.uvs.Size())
				fstream<<"/";
			if (f.uvs.Size())
				fstream<<(f.uvs[i]+1);
			if (f.normals.Size())
				fstream<<"/"<<(f.normals[i]+1);
		}
	}
	objFile.Close();
	return true;
}
Example #5
0
void SettingsHelper::SetGpsLocation(
    /* [in] */ const String& value)
{
    AutoPtr<IInterface> obj;
    mContext->GetSystemService(IContext::USER_SERVICE, (IInterface**)&obj);
    AutoPtr<IUserManager> um = IUserManager::Probe(obj);
    Boolean res;
    if (um->HasUserRestriction(IUserManager::DISALLOW_SHARE_LOCATION, &res), res) {
        return;
    }

    String GPS = ILocationManager::GPS_PROVIDER;
    Boolean enabled = GPS.Equals(value) ||
            value.StartWith(GPS + String(",")) ||
            value.EndWith(String(",") + GPS) ||
            value.Contains(String(",") + GPS + String(","));
    AutoPtr<ISettingsSecure> secure;
    CSettingsSecure::AcquireSingleton((ISettingsSecure**)&secure);
    AutoPtr<IContentResolver> resolver;
    mContext->GetContentResolver((IContentResolver**)&resolver);
    secure->SetLocationProviderEnabled(resolver, GPS, enabled);
}
Example #6
0
static bool StringContains(const String& str)
{
	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
	String self = vframe->Self;
	return self.Contains(str);
}
bool ShaderProgram::Link()
{
    Release();

    if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObjectName() || !pixelShader_->GetGPUObjectName())
        return false;

    object_.name_ = glCreateProgram();
    if (!object_.name_)
    {
        linkerOutput_ = "Could not create shader program";
        return false;
    }

    glAttachShader(object_.name_, vertexShader_->GetGPUObjectName());
    glAttachShader(object_.name_, pixelShader_->GetGPUObjectName());
    glLinkProgram(object_.name_);

    int linked, length;
    glGetProgramiv(object_.name_, GL_LINK_STATUS, &linked);
    if (!linked)
    {
        glGetProgramiv(object_.name_, GL_INFO_LOG_LENGTH, &length);
        linkerOutput_.Resize((unsigned)length);
        int outLength;
        glGetProgramInfoLog(object_.name_, length, &outLength, &linkerOutput_[0]);
        glDeleteProgram(object_.name_);
        object_.name_ = 0;
    }
    else
        linkerOutput_.Clear();

    if (!object_.name_)
        return false;

    const int MAX_NAME_LENGTH = 256;
    char nameBuffer[MAX_NAME_LENGTH];
    int attributeCount, uniformCount, elementCount, nameLength;
    GLenum type;

    glUseProgram(object_.name_);

    // Check for vertex attributes
    glGetProgramiv(object_.name_, GL_ACTIVE_ATTRIBUTES, &attributeCount);
    for (int i = 0; i < attributeCount; ++i)
    {
        glGetActiveAttrib(object_.name_, i, (GLsizei)MAX_NAME_LENGTH, &nameLength, &elementCount, &type, nameBuffer);

        String name = String(nameBuffer, nameLength);
        VertexElementSemantic semantic = MAX_VERTEX_ELEMENT_SEMANTICS;
        unsigned char semanticIndex = 0;

        // Go in reverse order so that "binormal" is detected before "normal"
        for (unsigned j = MAX_VERTEX_ELEMENT_SEMANTICS - 1; j < MAX_VERTEX_ELEMENT_SEMANTICS; --j)
        {
            if (name.Contains(ShaderVariation::elementSemanticNames[j], false))
            {
                semantic = (VertexElementSemantic)j;
                unsigned index = NumberPostfix(name);
                if (index != M_MAX_UNSIGNED)
                    semanticIndex = (unsigned char)index;
                break;
            }
        }

        if (semantic == MAX_VERTEX_ELEMENT_SEMANTICS)
        {
            URHO3D_LOGWARNING("Found vertex attribute " + name + " with no known semantic in shader program " +
                vertexShader_->GetFullName() + " " + pixelShader_->GetFullName());
            continue;
        }

        int location = glGetAttribLocation(object_.name_, name.CString());
        vertexAttributes_[MakePair((unsigned char)semantic, semanticIndex)] = location;
        usedVertexAttributes_ |= (1 << location);
    }

    // Check for constant buffers
#ifndef GL_ES_VERSION_2_0
    HashMap<unsigned, unsigned> blockToBinding;

    if (Graphics::GetGL3Support())
    {
        int numUniformBlocks = 0;

        glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
        for (int i = 0; i < numUniformBlocks; ++i)
        {
            glGetActiveUniformBlockName(object_.name_, (GLuint)i, MAX_NAME_LENGTH, &nameLength, nameBuffer);

            String name(nameBuffer, (unsigned)nameLength);

            unsigned blockIndex = glGetUniformBlockIndex(object_.name_, name.CString());
            unsigned group = M_MAX_UNSIGNED;

            // Try to recognize the use of the buffer from its name
            for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
            {
                if (name.Contains(shaderParameterGroups[j], false))
                {
                    group = j;
                    break;
                }
            }

            // If name is not recognized, search for a digit in the name and use that as the group index
            if (group == M_MAX_UNSIGNED)
                group = NumberPostfix(name);

            if (group >= MAX_SHADER_PARAMETER_GROUPS)
            {
                URHO3D_LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
                           " " + pixelShader_->GetFullName());
                continue;
            }

            // Find total constant buffer data size
            int dataSize;
            glGetActiveUniformBlockiv(object_.name_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
            if (!dataSize)
                continue;

            unsigned bindingIndex = group;
            // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
            // from that point onward
            ShaderType shaderType = VS;
            if (name.Contains("PS", false))
            {
                bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
                shaderType = PS;
            }

            glUniformBlockBinding(object_.name_, blockIndex, bindingIndex);
            blockToBinding[blockIndex] = bindingIndex;

            constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(shaderType, bindingIndex, (unsigned)dataSize);
        }
    }
#endif

    // Check for shader parameters and texture units
    glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORMS, &uniformCount);
    for (int i = 0; i < uniformCount; ++i)
    {
        glGetActiveUniform(object_.name_, (GLuint)i, MAX_NAME_LENGTH, nullptr, &elementCount, &type, nameBuffer);
        int location = glGetUniformLocation(object_.name_, nameBuffer);

        // Check for array index included in the name and strip it
        String name(nameBuffer);
        unsigned index = name.Find('[');
        if (index != String::NPOS)
        {
            // If not the first index, skip
            if (name.Find("[0]", index) == String::NPOS)
                continue;

            name = name.Substring(0, index);
        }

        if (name[0] == 'c')
        {
            // Store constant uniform
            String paramName = name.Substring(1);
            ShaderParameter parameter{paramName, type, location};
            bool store = location >= 0;

#ifndef GL_ES_VERSION_2_0
            // If running OpenGL 3, the uniform may be inside a constant buffer
            if (parameter.location_ < 0 && Graphics::GetGL3Support())
            {
                int blockIndex, blockOffset;
                glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
                glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
                if (blockIndex >= 0)
                {
                    parameter.offset_ = blockOffset;
                    parameter.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
                    store = true;
                }
            }
#endif

            if (store)
                shaderParameters_[StringHash(paramName)] = parameter;
        }
        else if (location >= 0 && name[0] == 's')
        {
            // Set the samplers here so that they do not have to be set later
            unsigned unit = graphics_->GetTextureUnit(name.Substring(1));
            if (unit >= MAX_TEXTURE_UNITS)
                unit = NumberPostfix(name);

            if (unit < MAX_TEXTURE_UNITS)
            {
                useTextureUnits_[unit] = true;
                glUniform1iv(location, 1, reinterpret_cast<int*>(&unit));
            }
        }
    }

    // Rehash the parameter & vertex attributes maps to ensure minimal load factor
    vertexAttributes_.Rehash(NextPowerOfTwo(vertexAttributes_.Size()));
    shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));

    return true;
}
Example #8
0
void JSVM::SendJSErrorEvent(const String& filename)
{
    duk_context* ctx = GetJSContext();

    using namespace JSError;

    VariantMap eventData;

    if (duk_is_string(ctx, -1))
    {
        eventData[P_ERRORNAME] = "(Unknown Error Name)";
        eventData[P_ERRORFILENAME] = "(Unknown Filename)";
        eventData[P_ERRORLINENUMBER] =  -1;
        eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
        eventData[P_ERRORSTACK] = "";
        SendEvent(E_JSERROR, eventData);
        return;
    }

    assert(duk_is_object(ctx, -1));

    duk_get_prop_string(ctx, -1, "fileName");

    if (duk_is_string(ctx, -1))
    {
        eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
    }
    else
    {
        eventData[P_ERRORFILENAME] = filename;
    }

    // Component script are wrapped within a closure, the line number
    // needs to be offset by this header
    duk_get_prop_string(ctx, -2, "lineNumber");
    int lineNumber = (int) (duk_to_number(ctx, -1));

    eventData[P_ERRORLINENUMBER] =  lineNumber;

    duk_get_prop_string(ctx, -3, "name");
    String name = duk_to_string(ctx, -1);
    eventData[P_ERRORNAME] = name;

    duk_get_prop_string(ctx, -4, "message");
    String message = duk_to_string(ctx, -1);
    eventData[P_ERRORMESSAGE] = message;

    // we're not getting good file/line from duktape on parser errors
    if (name == "SyntaxError")
    {
        lineNumber = -1;
        // parse line if we have it
        if (message.Contains("(line "))
        {
            if (!filename.Length())
                eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;

            unsigned pos = message.Find("(line ");
            const char* parse = message.CString() + pos + 6;
            String number;
            while (*parse >= '0' && *parse<='9')
            {
                number += *parse;
                parse++;
            }

            lineNumber = ToInt(number);

        }

        eventData[P_ERRORLINENUMBER] =  lineNumber;

    }

    duk_get_prop_string(ctx, -5, "stack");
    String stack = duk_to_string(ctx, -1);
    eventData[P_ERRORSTACK] = stack;

    duk_pop_n(ctx, 5);

    ATOMIC_LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
              filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());

    SendEvent(E_JSERROR, eventData);

}
Example #9
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 #10
0
Boolean ContainsFilter::MatchesValue(
    /* in */ const String& value)
{
    return value != NULL && value.Contains(mFilterValue);
}
void OverlayDisplayAdapter::UpdateOverlayDisplayDevicesLocked()
{
    AutoPtr<IContext> context = GetContext();

    AutoPtr<IContentResolver> cr;
    context->GetContentResolver((IContentResolver**)&cr);
    String value;
    Settings::Global::GetString(cr, ISettingsGlobal::OVERLAY_DISPLAY_DEVICES, &value);
    if (value.IsNull()) {
        value = String("");
    }

    if (value.Equals(mCurrentOverlaySetting)) {
        return;
    }
    mCurrentOverlaySetting = value;

    if (!mOverlays.IsEmpty()) {
        Slogger::I(TAG, "Dismissing all overlay display devices.");

        List<AutoPtr<OverlayDisplayHandle> >::Iterator iter = mOverlays.Begin();
        for (; iter != mOverlays.End(); ++iter) {
            (*iter)->DismissLocked();
        }
        mOverlays.Clear();
    }



    AutoPtr<ArrayOf<String> > parts;
    StringUtils::Split(value, String(";"), (ArrayOf<String> **)&parts);
    if (parts != NULL) {
        AutoPtr<IResources> resources;
        context->GetResources((IResources**)&resources);
        assert(resources != NULL);

        String part;
        Int32 count = 0, width, height, densityDpi;
        Boolean matched;
        ECode ec = NOERROR;
        for (Int32 i = 0; i < parts->GetLength(); ++i) {
            part = (*parts)[i];

            AutoPtr<IMatcher> matcher;
            SETTING_PATTERN->Matcher(part, (IMatcher**)&matcher);
            matcher->Matches(&matched);
            if (matched) {
                if (count >= 4) {
                    Slogger::W(TAG, "Too many overlay display devices specified: %s", value.string());
                    break;
                }

                IMatchResult* mr = IMatchResult::Probe(matcher);
                String strGroup;
                mr->Group(1, &strGroup);
                ec = StringUtils::Parse(strGroup, 10, &width);
                if (ec == (ECode)E_NUMBER_FORMAT_EXCEPTION) continue;
                mr->Group(2, &strGroup);
                ec = StringUtils::Parse(strGroup, 10, &height);
                if (ec == (ECode)E_NUMBER_FORMAT_EXCEPTION) continue;
                mr->Group(3, &strGroup);
                ec = StringUtils::Parse(strGroup, 10, &densityDpi);
                if (ec == (ECode)E_NUMBER_FORMAT_EXCEPTION) continue;

                String flagString;
                mr->Group(4, &flagString);
                if (width >= MIN_WIDTH && width <= MAX_WIDTH
                    && height >= MIN_HEIGHT && height <= MAX_HEIGHT
                    && densityDpi >= IDisplayMetrics::DENSITY_LOW
                    && densityDpi <= IDisplayMetrics::DENSITY_XXHIGH) {
                    Int32 number = ++count;

                    String name;
                    resources->GetString(R::string::display_manager_overlay_display_name, &name);
                    Int32 gravity = ChooseOverlayGravity(number);

                    Boolean secure = !flagString.IsNull() && flagString.Contains(",secure");

                    Slogger::I(TAG, "Showing overlay display device #%d: name=%s, width=%d, height=%d, densityDpi=%d, secure=%d",
                        number, name.string(), width, height, densityDpi, secure);

                    AutoPtr<OverlayDisplayHandle> handle = new OverlayDisplayHandle(this, name,
                        width, height, densityDpi, gravity, secure);
                    mOverlays.PushBack(handle);

                    continue;
                }
            }
            else if (part.IsEmpty()) {
                continue;
            }

            Slogger::W(TAG, "Malformed overlay display devices setting: %s", value.string());
        }
    }
}
Example #12
0
ScanResult* ParseScanResult(String line)
{
    if (line.IsNullOrEmpty()) {
        return NULL;
    }

    ScanResult* scanResult = NULL;

    /*
     * Cache implementation (LinkedHashMap) is not synchronized, thus,
     * must synchronized here!
     */
    String result[5];
    int resultCount = 0;

    AutoPtr<ArrayOf<Char32> > chars = line.GetChars();
    int lineLen = chars->GetLength();
    for (int tabBeg = 0, tabEnd = 0; tabEnd <= lineLen; ++tabEnd) {
        if (tabEnd == lineLen || (*chars)[tabEnd] == '\t') {
            if (tabEnd > tabBeg) {
                result[resultCount] = line.Substring(tabBeg, tabEnd);
                ++resultCount;
            }
            tabBeg = tabEnd + 1;
        }
    }

    if (3 <= resultCount && resultCount <= 5) {
        //String bssid = result[0];
        // bssid | frequency | level | flags | ssid
        // int frequency;
        // int level;
        // try {
        //     frequency = Integer.parseInt(result[1]);
        //     level = Integer.parseInt(result[2]);
            /* some implementations avoid negative values by adding 256
             * so we need to adjust for that here.
             */
        //     if (level > 0) level -= 256;
        // } catch (NumberFormatException e) {
        //     frequency = 0;
        //     level = 0;
        // }

        /*
         * The formatting of the results returned by
         * wpa_supplicant is intended to make the fields
         * line up nicely when printed,
         * not to make them easy to parse. So we have to
         * apply some heuristics to figure out which field
         * is the SSID and which field is the flags.
         */
        String ssid;
        String flags;
        if (resultCount == 4) {
            if (result[3].GetChar(0) == '[') {
                flags = result[3];
                ssid = "";
            }
            else {
                flags = "";
                ssid = result[3];
            }
        }
        else if (resultCount == 5) {
            flags = result[3];
            ssid = result[4];
        }
        else {
            // Here, we must have 3 fields: no flags and ssid
            // set
            flags = "";
            ssid = "";
        }

        // Do not add scan results that have no SSID set
        if (0 < ssid.Trim().GetLength()) {
            int security = -1;
            if (flags.Contains("WPA-PSK") || flags.Contains("WPA2-PSK"))
                security = 0;
            else if (flags.Contains("WEP"))
                security = 1;
            else if (flags.Contains("WPA2-EAP"))
                return NULL;//TODO:
            scanResult = new ScanResult();
            strcpy(scanResult->ssid, ssid);
            scanResult->security = security;
        }
    }

    return scanResult;
}