Esempio n. 1
0
void Application::InitPrimaryWindow()
{
	new Win32Device(mWidth, mHeight, mTitle.c_str());

	MainWindow()->RegisterClass();
	MainWindow()->InitInstance();
}
Esempio n. 2
0
/*----------------------------------------------------------------------------------------------
	Process the right+click delete.
	@param pcmd Menu command
	@return true if sucessful
----------------------------------------------------------------------------------------------*/
bool CleDeSplitChild::CmdDelete(Cmd * pcmd)
{
	if ((dynamic_cast<RecMainWnd *>(MainWindow())->GetRecordClid() == kclidPartOfSpeech)
		&& pcmd->m_rgn[0] == kPopupMenu
		&& m_vdfe[m_idfe]->GetIndent() > 0)
			return CmdDeleteObject(pcmd);

	CleMainWnd * pcmw = dynamic_cast<CleMainWnd *>(MainWindow());
	AssertPtr(pcmw);
	return pcmw->CmdEditDelete(pcmd);
}
Esempio n. 3
0
/*----------------------------------------------------------------------------------------------
	Respond to any of the items in the Insert submenu.
	@param pcmd Menu command info.
	@return true to stop further processing.
----------------------------------------------------------------------------------------------*/
bool CleDeSplitChild::InsertEntry(Cmd * pcmd)
{
	AssertPtr(pcmd);

	CleMainWnd * pcmw = dynamic_cast<CleMainWnd *>(MainWindow());
	if (pcmw)
	{
		switch (pcmd->m_cid)
		{
		case kcidInsItem:
			::SendMessage(pcmw->Hwnd(), WM_COMMAND, kcidInsListItem, 0);
			return true;
		case kcidInsItemBef:
			::SendMessage(pcmw->Hwnd(), WM_COMMAND, kcidInsListItemBef, 0);
			return true;
		case kcidInsItemAft:
			::SendMessage(pcmw->Hwnd(), WM_COMMAND, kcidInsListItemAft, 0);
			return true;
		case kcidInsSubItem:
			::SendMessage(pcmw->Hwnd(), WM_COMMAND, kcidInsListSubItem, 0);
			return true;
		default:
			return false;
		}
	}
	return false;
}
Esempio n. 4
0
/*----------------------------------------------------------------------------------------------
	Add menu items for the right-click context Insert menu over tree pane.
----------------------------------------------------------------------------------------------*/
void CleDeSplitChild::AddContextInsertItems(HMENU & hmenu)
{
	StrApp str;

	CleMainWnd * pcmw = dynamic_cast<CleMainWnd *>(MainWindow());
	Assert(pcmw);

	PossListInfo * ppli = pcmw->GetPossListInfoPtr();
	AssertPtr(ppli);

	if (!ppli->GetIsSorted())
	{
		str.Assign(_T("List Item &Above"));
		::AppendMenu(hmenu, MF_STRING, kcidInsItemBef, str.Chars());
		str.Assign(_T("List Item &Below"));
		::AppendMenu(hmenu, MF_STRING, kcidInsItemAft, str.Chars());
	}
	else
	{
		str.Assign(_T("List &Item"));
		::AppendMenu(hmenu, MF_STRING, kcidInsItem, str.Chars());
	}
	if (ppli->GetDepth() != 1)
	{
		str.Assign(_T("List &Subitem"));
		::AppendMenu(hmenu, MF_STRING, kcidInsSubItem, str.Chars());
	}
}
Esempio n. 5
0
/*----------------------------------------------------------------------------------------------
	Set the startup information this window to the promoted entry.
	@param hvo The id of the entry or subentry that has been promoted.
----------------------------------------------------------------------------------------------*/
void CleDeSplitChild::PromoteSetup(HVO hvo)
{
	Assert(hvo);
	// At the moment we are assuming hvo is a CmPossibility (or subclass). At some point this
	// will probably change, which will require additional code.
	Vector<HVO> vhvo;
	Vector<int> vflid;
	// Set up the path to hvo.
	vhvo.Push(hvo);
	// Add owning records, if there are any, until we reach the main record.
	CustViewDaPtr qcvd;
	m_qlpi->GetDataAccess(&qcvd);
	AssertPtr(qcvd);
	RecMainWnd * prmw = dynamic_cast<RecMainWnd *>(MainWindow());
	AssertPtr(prmw);
	HVO hvoRoot = prmw->GetRootObj();
	HVO hvoOwn;
	while (hvo)
	{
		CheckHr(qcvd->get_ObjOwner(hvo, &hvoOwn));
		hvo = hvoOwn;
		if (hvo == hvoRoot || !hvo)
			break;
		vhvo.Insert(0, hvo);
		vflid.Insert(0, kflidCmPossibility_SubPossibilities);
	}
	prmw->SetStartupInfo(vhvo.Begin(), vhvo.Size(), vflid.Begin(), vflid.Size(), 0, 0);
}
Esempio n. 6
0
/*----------------------------------------------------------------------------------------------
	Synchronize all windows in this application with any changes made in the database.
	@param sync -> The information describing a given change.
----------------------------------------------------------------------------------------------*/
bool CleDeSplitChild::Synchronize(SyncInfo & sync)
{
	SuperClass::Synchronize(sync);

	switch(sync.msg)
	{
	case ksyncAddPss:
	case ksyncDelPss:
	case ksyncPossList:
		{
			RecMainWnd * prmw = dynamic_cast<RecMainWnd *>(MainWindow());
			Assert(prmw);
			int chvo = prmw->Records().Size(); // Need to handle deleting last item.
			if (m_vdfe.Size())
			{
				if (chvo && prmw->Records()[prmw->CurRecIndex()].hvo == m_vdfe[0]->GetOwner())
					return true; // No change.
				// Otherwise our record has changed, so we need to redisplay the record.
				CloseAllEditors();
			}
			if (chvo)
				SetRootObj(prmw->Records()[prmw->CurRecIndex()], true);
			::InvalidateRect(m_hwnd, NULL, false);
		}
		return true;

	default:
		break;
	}
	return true;
}
Esempio n. 7
0
/*----------------------------------------------------------------------------------------------
	Check to see if we are editing a new record, if so, update the date modified on the old
	record if changes were made.
----------------------------------------------------------------------------------------------*/
void CleDeSplitChild::BeginEdit(AfDeFieldEditor * pdfe)
{
	HVO hvoNew = pdfe->GetObj();
	if (m_hvoLastObj && m_hvoLastObj != hvoNew)
	{
		// We've opened an editor on a new object.
		CustViewDaPtr qcvd;
		m_qlpi->GetDataAccess(&qcvd);
		AssertPtr(qcvd);
		int clid;
		// Find out if this is a kind of CmPossibility.
		CheckHr(qcvd->get_ObjClid(m_hvoLastObj, &clid));
		IFwMetaDataCachePtr qmdc;
		m_qlpi->GetDbInfo()->GetFwMetaDataCache(&qmdc);
		AssertPtr(qmdc);
		do
		{
			if (clid == kclidCmPossibility)
			{
				// The object has a DateModified property, so see that it is current.
				RecMainWnd * prmw = dynamic_cast<RecMainWnd *>(MainWindow());
				Assert(prmw);
				prmw->UpdateDateModified(m_hvoLastObj, kflidCmPossibility_DateModified);
				break;
			}
			ulong uclid;
			qmdc->GetBaseClsId(clid, &uclid);
			clid = (int)uclid;
		} while (clid != 0);
	}
}
Esempio n. 8
0
/*----------------------------------------------------------------------------------------------
	Handle the redo command by passing it on to the main window.
	@param pcmd menu command
	@return true if successful.
----------------------------------------------------------------------------------------------*/
bool AfDeFeEdBoxBut::DeEdit::CmdEditRedo(Cmd * pcmd)
{
	m_pdee->EndTempEdit();
	RecMainWnd * pwnd = dynamic_cast<RecMainWnd *>(MainWindow());
	Assert(pwnd);
	pwnd->CmdEditRedo(pcmd);
	// Note, due to FullRefresh, this field editor is deleted at this point.
	return true;
}
Esempio n. 9
0
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrevInst,LPSTR pCmdline,int cmd){
	MSG msg;
	MainWindow MainWindow(hInst);
	while(GetMessage(&msg,NULL,0,0)){
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return 0;
}
Esempio n. 10
0
int
main(int argc, char *argv[])
{
	Uint flags = AG_VIDEO_RESIZABLE;
	int c, i, fps = -1;
	char *s;

	if (AG_InitCore("agar-bench", 0) == -1) {
		fprintf(stderr, "%s\n", AG_GetError());
		return (1);
	}

	while ((c = getopt(argc, argv, "?vegt:r:T:")) != -1) {
		extern char *optarg;

		switch (c) {
		case 'v':
			exit(0);
		case 'g':
			flags |= AG_VIDEO_OPENGL;
			break;
		case 't':
			AG_TextParseFontSpec(optarg);
			break;
		case 'T':
			AG_SetString(agConfig, "font-path", optarg);
			break;
		case 'r':
			fps = atoi(optarg);
			break;
		case '?':
		default:
			printf("%s [-vfFgG] [-w width] [-h height] [-r fps]"
			       " [-t font,size,flags] [-T font-path]\n",
			    agProgName);
			exit(0);
		}
	}

	if (AG_InitVideo(640, 480, 32, flags) == -1) {
		fprintf(stderr, "%s\n", AG_GetError());
		return (-1);
	}
	AG_BindGlobalKey(AG_KEY_ESCAPE, AG_KEYMOD_ANY, AG_Quit);
	AG_BindGlobalKey(AG_KEY_F8, AG_KEYMOD_ANY, AG_ViewCapture);
	AG_SetRefreshRate(fps);

	MainWindow();

	AG_EventLoop();
	AG_Destroy();
	return (0);
fail:
	AG_Destroy();
	return (1);
}
Esempio n. 11
0
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
	CPS2VM virtualMachine;
	CMainWindow MainWindow(virtualMachine);
	MainWindow.Loop();
#ifdef VTUNE_ENABLED
	iJIT_NotifyEvent(iJVM_EVENT_TYPE_SHUTDOWN, NULL);
#endif
	return 0;
}
Esempio n. 12
0
UserInterface * MainUI()
{
	AppWindow * mainWindow = MainWindow();
	if (!mainWindow)
	{
		LogMain("MainUI(): No main AppWindow!", WARNING);
		return NULL;
	}
	return mainWindow->GetUI();
}
Esempio n. 13
0
void GMSetResolution::Process()
{
	if (naturalRatio)
	{
		graphicsState->renderResolution = MainWindow()->ClientAreaSize();
		graphicsState->resolutionLocked = false;
		return;
	}
	if (staticRatio)
	{
		graphicsState->relativeResolution = ratio;
		graphicsState->renderResolution = MainWindow()->ClientAreaSize() * ratio;
		graphicsState->resolutionLocked = false;
		return;
	}
	if (graphicsState->resolutionLocked && !lock)
		return;
	graphicsState->renderResolution = res * graphicsState->relativeResolution;
	graphicsState->resolutionLocked = lock;
}
void handleTreeNodeExport(ActionEventDetails* const details,
                          Tree* const editorTree)
{
    boost::any SelectedComp(editorTree->getLastSelectedPathComponent());

    //Get the tree selection
    try
    {
        FieldContainerTreeModel::ContainerFieldIdPair ThePair(boost::any_cast<FieldContainerTreeModel::ContainerFieldIdPair>(SelectedComp));

        if(ThePair._FieldID == 0 &&
           ThePair._Container != NULL)
        {
            std::vector<WindowEventProducer::FileDialogFilter> ExportFileFilters;
            ExportFileFilters.push_back(WindowEventProducer::FileDialogFilter("Field Container File","xml"));
            ExportFileFilters.push_back(WindowEventProducer::FileDialogFilter("All Files","*"));

            //Export File
            BoostPath InitialFilePath("./Export.xml");

            WindowEventProducer* MainWindow(editorTree->getParentWindow()->getParentDrawingSurface()->getEventProducer());
            BoostPath ExportFilePath;
            ExportFilePath =MainWindow->saveFileDialog("Save Field Container",
                                                       ExportFileFilters,
                                                       InitialFilePath.filename(),
                                                       InitialFilePath.parent_path(),
                                                       true);

            if(!ExportFilePath.empty())
            {
                if(ExportFilePath.extension().empty())
                {
                    ExportFilePath = ExportFilePath.string() + ".xml";
                }

                FCFileType::FCPtrStore Containers;
                Containers.insert(ThePair._Container);

                FCFileType::FCTypeVector IgnoreTypes;

                FCFileHandler::the()->write(Containers,ExportFilePath,IgnoreTypes);
            }
        }
    }
    catch(boost::bad_any_cast &ex)
    {
        SWARNING << ex.what() << std::endl;
    }
}
Esempio n. 15
0
/*----------------------------------------------------------------------------------------------
	Clear out the window contents, and especially any active database connections, when the
	project is (about to be) changed. Return true if the close is OK.
	@return true if the close is OK.
----------------------------------------------------------------------------------------------*/
bool CleDeSplitChild::CloseProj()
{
	// Close current editor if there is one.
	if (!CloseEditor())
		return false;
	if (m_fNeedSync)
	{
		// Notify other apps of change.
		CleMainWnd * pcmw = dynamic_cast<CleMainWnd *>(MainWindow());
		Assert(pcmw);
		SyncInfo sync(ksyncPossList, pcmw->GetRootObj(), 0);
		m_qlpi->StoreSync(sync);
	}
	return SuperClass::CloseProj();
}
Esempio n. 16
0
/*----------------------------------------------------------------------------------------------
	Process right button down (WM_LBUTTONDOWN). Activates an editor window if needed.
	@param grfmk Indicates whether various virtual keys are down.
	@param xp The x-coord of the mouse relative to the upper-left corner of the client.
	@param yp The y-coord of the mouse relative to the upper-left corner of the client.
	@return Return true if processed.
----------------------------------------------------------------------------------------------*/
bool CleDeSplitChild::OnRButtonDown(uint grfmk, int xp, int yp)
{
	m_fNeedSync = false; // Clear from previous EndEdits.
	bool f = SuperClass::OnRButtonDown(grfmk, xp, yp);
	if (m_fNeedSync)
	{
		// Update all lists now that we've changed.
		CleMainWnd * pcmw = dynamic_cast<CleMainWnd *>(MainWindow());
		Assert(pcmw);
		SyncInfo sync(ksyncPossList, pcmw->GetRootObj(), 0);
		m_qlpi->StoreAndSync(sync);
		m_fNeedSync = false;
	}
	return f;
}
Esempio n. 17
0
/*----------------------------------------------------------------------------------------------
	If there is another editable field above the currently open field, this closes the current
	field and opens the previous editable field. dxpCursor allows the insertion point in
	the new field to be located at some point other than the left margin. fTopCursor determines
	whether the insertion point is placed on the top or bottom line.
	@param dxpCursor Horiz. pixels from the left field margin for the insertion point.
	@param fTopCursor True if the insertion point is to be placed on the top field line.
	@return True if it succeeded in opening a new field. False if the current field editor
		can't be closed or if there are no editable fields above the current field.
----------------------------------------------------------------------------------------------*/
bool CleDeSplitChild::OpenPreviousEditor(int dxpCursor, bool fTopCursor)
{
	m_fNeedSync = false; // Clear from previous EndEdits.
	bool f = SuperClass::OpenPreviousEditor(dxpCursor, fTopCursor);
	if (m_fNeedSync)
	{
		// Update all lists now that we've changed.
		CleMainWnd * pcmw = dynamic_cast<CleMainWnd *>(MainWindow());
		Assert(pcmw);
		SyncInfo sync(ksyncPossList, pcmw->GetRootObj(), 0);
		m_qlpi->StoreAndSync(sync);
		m_fNeedSync = false;
	}
	return f;
}
Esempio n. 18
0
/*----------------------------------------------------------------------------------------------
	This method checks for duplicates in list names.  If the given name exists then return true.

	@param pszName name to check to see if it exists.
	@return True if name already exists.
----------------------------------------------------------------------------------------------*/
bool ListsPropDlg::CheckName(const achar * pszName)
{
	AfMainWnd * pafw = MainWindow();
	AssertPtr(pafw);
	AfLpInfo * plpi = pafw->GetLpInfo();
	AssertPtr(plpi);
	Vector<HVO> & vhvo = plpi->GetPsslIds();

	AfDbInfoPtr qdbi = plpi->GetDbInfo();
	AssertPtr(qdbi);
	IOleDbEncapPtr qode;
	qdbi->GetDbAccess(&qode);

	StrAnsi sta;
	int i;
	StrUni stuIds;
	int cv = vhvo.Size();
	Assert(cv);

	ComBool fIsNull;
	ComBool fMoreRows;
	ULONG cbSpaceTaken;
	IOleDbCommandPtr qodc;

	const int kcchBuffer = MAX_PATH;
	OLECHAR rgchName[kcchBuffer];
	HVO hvo;
	StrUni stu;
	for (i = 0; i < cv; ++i)
	{
		hvo = vhvo[i];
		stu.Format(L"exec GetOrderedMultiTxt '%d', %d",
			hvo, kflidCmMajorObject_Name);
		CheckHr(qode->CreateCommand(&qodc));
		CheckHr(qodc->ExecCommand(stu.Bstr(), knSqlStmtStoredProcedure));
		CheckHr(qodc->GetRowset(0));
		CheckHr(qodc->NextRow(&fMoreRows));
		Assert(fMoreRows); // This proc should always return something.
		CheckHr(qodc->GetColValue(1, reinterpret_cast <BYTE *>(rgchName),
			kcchBuffer * isizeof(OLECHAR), &cbSpaceTaken, &fIsNull, 2));
		sta = rgchName;
		if (hvo != m_hvoObj && sta.Equals(pszName))
			return false;
	}
	return true;
}
Esempio n. 19
0
// Checks mouse position and casts a ray. Will return all entities along the ray, starting with the closest one.
void FirstPersonPlayerProperty::UpdateTargetsByCursorPosition()
{
	Ray ray;
	AppWindow * activeWindow = ActiveWindow();
	if (activeWindow != MainWindow())
		return;
	// Try to get ray.
	if (!activeWindow->GetRayFromScreenCoordinates(inputState->mousePosition, ray))
		return;

	// Do ray cast within the physics system
	PMRaycast * raycast = new PMRaycast(ray);
	raycast->relevantEntity = owner;
	raycast->msg = "UpdateTargetsByCursorPosition";
	PhysicsQueue.Add(raycast);

	/// React to message of it later on.
}
Esempio n. 20
0
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdParam,int nCmdShow) // 메인함수.
{

//    ShowWindow(GetConsoleWindow(),SW_HIDE); // 콘솔창이 사라지도록  하는 함수이다.

    g_hInst=hInstance;
    MSG Message;

    window_main=MainWindow(hInstance,"3DPaint",IDR_MENU1); // MainWindow 인스턴스 생성

    window_main.show_window(50,50,1000,700); // window 출력

    while(GetMessage(&Message,0,0,0))  // 메세지처리
    {
        TranslateMessage(&Message);
        DispatchMessage(&Message);
    }
    return 0;
}
Esempio n. 21
0
/*----------------------------------------------------------------------------------------------
	Make the root box.
----------------------------------------------------------------------------------------------*/
void TssEdit::MakeRoot(IVwGraphics * pvg, ILgWritingSystemFactory * pwsf, IVwRootBox ** pprootb)
{
	AssertPtr(pvg);
	AssertPtrN(pwsf);
	AssertPtr(pprootb);

	*pprootb = NULL;

	IVwRootBoxPtr qrootb;
	qrootb.CreateInstance(CLSID_VwRootBox);
	CheckHr(qrootb->SetSite(this));
	HVO hvo = khvoString;
	int frag = kfrString;

	// Set up a new view constructor.
	ComBool fRTL = FALSE;
	IWritingSystemPtr qws;
	Assert(pwsf == m_qwsf.Ptr());
	CheckHr(pwsf->get_EngineOrNull(m_wsBase, &qws));
	if (qws)
		CheckHr(qws->get_RightToLeft(&fRTL));
	TssEditVcPtr qtevc;
	qtevc.Attach(NewObj TssEditVc(this, m_nEditable, m_fShowTags, fRTL));

	CheckHr(m_qcda->putref_WritingSystemFactory(pwsf));
	CheckHr(qrootb->putref_DataAccess(m_qcda));

	AfMainWnd * pafw = MainWindow();
	AssertPtrN(pafw);
	AfStylesheet * pss = NULL;
	AfLpInfo * plpi = pafw->GetLpInfo();
	if (plpi)
	{
		pss = plpi->GetAfStylesheet();
		// This allows it to receive updates to style defns.
		pafw->RegisterRootBox(qrootb);
	}
	IVwViewConstructor * pvvc = qtevc;
	CheckHr(qrootb->SetRootObjects(&hvo, &pvvc, &frag, pss, 1));

	*pprootb = qrootb.Detach();
}
Esempio n. 22
0
void SayGoodbye(void)
{
  struct viewporttype viewinfo; 	/* Structure to read viewport	*/
  int h, w;

  MainWindow( "== Finale ==" );

  getviewsettings( &viewinfo ); 	/* Read viewport settings	*/
  changetextstyle( TRIPLEX_FONT, HORIZ_DIR, 4 );
  settextjustify( CENTER_TEXT, CENTER_TEXT );

  h = viewinfo.bottom - viewinfo.top;
  w = viewinfo.right  - viewinfo.left;
  outtextxy( w/2, h/2, "That's all, folks!" );

  StatusLine( "Press any key to EXIT" );
  getch();

  cleardevice();			/* Clear the graphics screen	*/

}
Esempio n. 23
0
int WINAPI WinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPSTR /*lpszArgs*/, int /*nWinMode*/)
{
    try
    {
        CoInitialize(NULL);
        AppInit(&Notify(), CPath(CPath::MODULE_DIRECTORY), __argc, __argv);
        if (!g_Lang->IsLanguageLoaded())
        {
            CLanguageSelector().Select();
        }

        //Create the main window with Menu
        WriteTrace(TraceUserInterface, TraceDebug, "Create Main Window");
        CMainGui MainWindow(true, stdstr_f("Project64 %s", VER_FILE_VERSION_STR).c_str()), HiddenWindow(false);
        CMainMenu MainMenu(&MainWindow);
        CDebuggerUI Debugger;
        g_Debugger = &Debugger;
        g_Plugins->SetRenderWindows(&MainWindow, &HiddenWindow);
        Notify().SetMainWindow(&MainWindow);
        CSupportWindow SupportWindow;

        if (g_Settings->LoadStringVal(Cmd_RomFile).length() > 0)
        {
            MainWindow.Show(true);	//Show the main window
            //N64 ROM or 64DD Disk
            stdstr ext = CPath(g_Settings->LoadStringVal(Cmd_RomFile)).GetExtension();
            if (!(_stricmp(ext.c_str(), "ndd") == 0))
            {
                //File Extension is not *.ndd so it should be a N64 ROM
                CN64System::RunFileImage(g_Settings->LoadStringVal(Cmd_RomFile).c_str());
            }
            else
            {
                //Ext is *.ndd, so it should be a disk file.
                if (!CPath(g_Settings->LoadStringVal(File_DiskIPLPath)).Exists() || !g_BaseSystem->RunDiskImage(g_Settings->LoadStringVal(Cmd_RomFile).c_str()))
                {
                    if (!CPath(g_Settings->LoadStringVal(File_DiskIPLPath)).Exists()) { g_Notify->DisplayWarning(MSG_IPL_REQUIRED); }
                    CPath FileNameIPL;
                    const char * Filter = "64DD IPL ROM Image (*.zip, *.7z, *.?64, *.rom, *.usa, *.jap, *.pal, *.bin)\0*.?64;*.zip;*.7z;*.bin;*.rom;*.usa;*.jap;*.pal\0All files (*.*)\0*.*\0";
                    if (FileNameIPL.SelectFile(NULL, g_Settings->LoadStringVal(RomList_GameDir).c_str(), Filter, true))
                    {
                        g_Settings->SaveString(File_DiskIPLPath, (const char *)FileNameIPL);
                        g_BaseSystem->RunDiskImage(g_Settings->LoadStringVal(Cmd_RomFile).c_str());
                    }
                }
            }
        }
        else
        {
            SupportWindow.Show(reinterpret_cast<HWND>(MainWindow.GetWindowHandle()));
            if (UISettingsLoadBool(RomBrowser_Enabled))
            {
                WriteTrace(TraceUserInterface, TraceDebug, "Show Rom Browser");
                //Display the rom browser
                MainWindow.ShowRomList();
                MainWindow.Show(true);	//Show the main window
                MainWindow.HighLightLastRom();
            }
            else
            {
                WriteTrace(TraceUserInterface, TraceDebug, "Show Main Window");
                MainWindow.Show(true);	//Show the main window
            }
        }

        //Process Messages till program is closed
        WriteTrace(TraceUserInterface, TraceDebug, "Entering Message Loop");
        MainWindow.ProcessAllMessages();
        WriteTrace(TraceUserInterface, TraceDebug, "Message Loop Finished");

        if (g_BaseSystem)
        {
            g_BaseSystem->CloseCpu();
            delete g_BaseSystem;
            g_BaseSystem = NULL;
        }
        WriteTrace(TraceUserInterface, TraceDebug, "System Closed");
    }
    catch (...)
    {
        WriteTrace(TraceUserInterface, TraceError, "Exception caught (File: \"%s\" Line: %d)", __FILE__, __LINE__);
        MessageBox(NULL, stdstr_f("Exception caught\nFile: %s\nLine: %d", __FILE__, __LINE__).c_str(), "Exception", MB_OK);
    }
    AppCleanup();
    CoUninitialize();
    return true;
}
Esempio n. 24
0
/// If no cloud-system, spawns globally, based on the given boundaries (.
void PrecipitationSystem::SpawnNewGlobal(int timeInMs)
{
	/// Require 20+ fps.
	timeInMs = timeInMs % 50;
	// Try and emit each particles that the emitter wants to emit.
	/// check size of the emitter.
	float area = globalEmitter.SurfaceArea();
	int dropsPerSecond = area * rainAmount;
	int dropsToEmit = dropsPerSecond * timeInMs * 0.001f;

	Vector3f rainSpeed = Vector3f(0,-emissionVelocity,0);
	int seconds = altitude / AbsoluteValue(rainSpeed.y) + 3;

	/// Assume 1 primary global camera.
	Vector3f cameraPosition;
	AppWindow * window = MainWindow();
	if (window)
	{
		Camera * camera = window->MainViewport()->camera;
		if (camera)
		{
			cameraPosition = camera->Position();
		}
	}


	Vector3f cameraOffset = cameraPosition; // + camera->Velocity();
	Vector3f positionOffsetDueToWind = -weather->globalWind * seconds;
	Vector3f allPositionOffsets = cameraOffset + positionOffsetDueToWind + Vector3f(0,altitude,0);
	Vector3f position;
	Vector3f velocity;
	Vector2f pScale;
	float lifeTime;
	Vector4f pColor;

	for (int j = 0; j < dropsToEmit; ++j)
	{
		// Grab free index.
		int freeIndex = aliveParticles;
		// Skip if reaching max.
		if (freeIndex >= this->maxParticles)
		{
//				std::cout<<"\nEmitter unable to spawn particle. Max particles reached.";
			break;
		}
#ifdef SSE_PARTICLES
		// Position based on the global emitter (default an XZ plane.
		globalEmitter.Position(position);
		// Add random from 0 to 1.0 to get some variation in height?
		position.y += rand()*oneDivRandMaxFloat;
		// Add all offsets, such as altitude, camera position and offset due to wind.
		position += allPositionOffsets;
		lifeTime = seconds;
		/// Big rain (5 mm), 9 m/s, drizzle (0.5mm), 2 m/s.
		velocity = rainSpeed;

		/// Copy over data.
		positionsSSE[freeIndex].data = position.data;
		colorsSSE[freeIndex].data = color.data;
		velocitiesSSE[freeIndex].data = rainSpeed.data;
		float floats[4] = {lifeTime , 0, scale.x, scale.y};
		ldsSSE[freeIndex].data = _mm_loadu_ps(floats);
		/*
		ldsSSE[freeIndex].x = lifeTime;
		ldsSSE[freeIndex].y = 0;
		ldsSSE[freeIndex].z = scale.x;
		ldsSSE[freeIndex].w = scale.y;
		*/
		// Increment amount of living particles.
		++aliveParticles;
	
#else // Not SSE_PARTICLES
		Vector3f & position = positions[freeIndex];
		Vector3f & velocity = velocities[freeIndex];
		Vector2f & pScale = scales[freeIndex];
		float & lifeTime = lifeTimes[freeIndex];
		Vector4f & pColor = colors[freeIndex];

		// Position based on the global emitter (default an XZ plane.
		globalEmitter.Position(position);
		// Add random from 0 to 1.0 to get some variation in height?
		position.y += rand()*oneDivRandMaxFloat;
		// Move up position?
		position.y += altitude;
		position += cameraPosition;

		lifeTime = seconds;
		/// Big rain (5 mm), 9 m/s, drizzle (0.5mm), 2 m/s.
		velocity = rainSpeed;
		// Reset duration to 0 to signify that it is newly spawned.
		lifeDurations[freeIndex] = 0;
		// Increment amount of living particles.
		++aliveParticles;
		// Big scale and color for the time being.
		pScale = scale;
		pColor = color;
#endif
	}
}
Esempio n. 25
0
	/*COM1 0x3F8
	  COM2 0x2F8
	  COM3 0X3E8
	  COM4 0X2E8*/
#define BufferSize 1000
	void init_port();/*PORT SETTING*/
	void main()
	{

		int gd=VGA,gm=VGAHI;/*InIt Graphics Driver*/
		long int HRead,BRead;/*file stream handler and number of bytes read*/
		char RBuffer[BufferSize];/*read buffer*/
		unsigned long int FileSize=0;/*file size*/
		unsigned long int NoOfByD=0;/*number of byte done*/
		unsigned long int NumBuff1000;/*number of buffers.*/
		int GotFromPort;/*to store data received from port*/
		unsigned long int CurPos=0;/*pointer position in file*/
		unsigned int i,g;
		char FileName[30];/*FILE NAME*/
		char FileSizeC[30];/*file size in char form*/
		char NoOfBuffC[30];/* no of buffer in char form*/
		char x[1];/*to convert int to num from CP.*/
		int KeyInput=0,sta=1;
		initgraph(&gd,&gm,"\\tc\\bgi");/*init graphics*/
		cleardevice();
		init_port();/*Initilize the COM port for communication*/
		MainWindow("COM PORT COMMUNICATION UTILITY");
		Boxes(30,60,360,180,0,"SELECT");
		Show();
		setcolor(14);
		outtextxy(Left+60,Top+30,"COM PORT Communication Utility.");
		outtextxy(450,430,"Sameer Rajendra Dubey");
		outtextxy(450,450,"T.Y.B.Sc ELECTRONICS");
		outtextxy(450,440,"ROLL NUMBER : 317");
		Menu(1);
		for(;;)
		{
			KeyInput=getch();
			if(KeyInput == 27)
			{
				exit(0);
			}
			else if(KeyInput == 80)/*Down arrow key*/
			{
				switch(sta)
				{
					case 1:
					{
						Menu(2);
						sta=2;
						break;
					}
					case 2:
					{       Menu(3);
						sta=3;
						break;
					}
					case 3:
					{       Menu(4);
						sta=4;
						break;
					}
					case 4:
					{       Menu(1);
						sta=1;
						break;
					}
				}
			}
			else if(KeyInput==72)/*Uparrow key*/
			{
				switch(sta)
				{
					case 1:
					{       Menu(4);
						sta=4;
						break;
					}
					case 2:
					{       Menu(1);
						sta=1;
						break;
					}
					case 3:
					{       Menu(2);
						sta=2;
						break;
					}
					case 4:
					{       Menu(3);
						sta=3;
						break;
					}
				}
			}
			else if(KeyInput == 13)/*enter key*/
			{
				if(sta==4)
				{
					cleardevice();
					closegraph();
					exit(0);
				}
				else
				{
					break;
				}
			}
		}
		if(sta==1)/*recieve file*/
		{
			int c,ch;
			gotoxy(14,10);
			InputBox("Recieve File");
			scanf("%s",&FileName);
			HRead=sopen(FileName,O_RDWR|O_BINARY|O_CREAT,SH_DENYNO,S_IREAD|S_IWRITE);/*OPEN FILE*/
			outtextxy(Left+10,Top+120,"This terminal is ready to recieve a file.");
			setcolor(14);
			outtextxy(Left+10,Top+140,"when done press Esc to Exit");
			c=inport(PORT1+5);/*CHECK IF RECIEVE DATA*/
			if(c&1)
			{
				ch=inport(PORT1);
			}
			outportb(PORT1,100);/*SEND CHARACTER 'd' TO REMOTE TERMINAL.*/
			for(;;) /*start copy*/
			{
				c=inportb(PORT1+5);
					if(c&1)
					{
						ch=inport(PORT1);
						x[0]=ch;
						BRead=write(HRead,x,1);
						outportb(PORT1,100);
					}
					if(kbhit())
					{
						char T=getch();
						if(T == 27)
						{
							close(HRead);
							cleardevice();
							closegraph();
							exit(0);
						}
					}
				}
			}
			else if(sta == 2)
			{
				char choice;
				Top=260;
				Left=80;
				for(;;)/*Do until we get a valid file name */
				{
					gotoxy(14,10);
					MainWindow("COM PORT UTILITY");
					InputBox("Send File.");
					scanf("%s",&FileName);
					HRead=open(FileName,O_RDONLY|O_BINARY);
					FileSize=filelength(HRead);
					if(HRead>0)/*valid file*/
					{
						int c=0;
						if(FileSize>BufferSize)/*calculate the number of buffers.*/
						{
							NumBuff1000=(FileSize/BufferSize);
						}
						else
						{
							NumBuff1000=1;
						}
						if(NumBuff1000*BufferSize<FileSize)
						{
							++NumBuff1000;
						}
						min=0;/*assign min max values to status bar*/
						max=NumBuff1000;
						Boxes(30,60,300,180,0,"Send File");
						Show();
						setcolor(15);
						outtextxy(Left+10,Top+30,"File Name:");
						outtextxy(Left+10,Top+40,"File Size:");
						outtextxy(Left+10,Top+50,"Number Of Buffer:");
						setcolor(14);
						outtextxy(Left+150,Top+30,FileName);
						ltoa(FileSize,FileSizeC,10);
						ltoa(NumBuff1000,NoOfBuffC,10);
						outtextxy(Left+150,Top+50,NoOfBuffC);
						outtextxy(Left+150,Top+40,FileSizeC);
						outtextxy(Left+10,Top+80,"after making other terminal");
						outtextxy(Left+10,Top+90,"Ready press any key to start.");
						setcolor(15);
						ShowBar(Left+170,200,10,150);
						Refresh(0);
						KeyInput=getch();
						if(KeyInput == 27)
						{
							cleardevice();
							closegraph();
							exit(0);
						}
						for(i=1;i<=NumBuff1000;i++)/*all buffers send one by one */
						{
							CurPos=tell(HRead);/*get current pos of pointer*/
							BRead=read(HRead,RBuffer,BufferSize);
							CurPos+=BufferSize;
							lseek(HRead,CurPos,SEEK_SET);/*update ptr*/
							CurPos=tell(HRead);
							g=0;
							ShowBar(Left+170,200,10,150);
							Refresh(i);
							do
							{
								c=inportb(PORT1+5);/*CHECK THE DATA*/
								if(c&1)
								{
									GotFromPort=inport(PORT1);/*get data*/
									if(GotFromPort==100)/*if we get d*/
									{
										outportb(PORT1,RBuffer[g]);/*send char to serial port*/
										NoOfByD++;
										g++;
									}
								}
							}while(g<BRead);
						}               /*end for*/
						break;
					}/*end if (valid file)*/
					else
					{

						Boxes(80,260,450,120,4,"    Error !!!");
						Show();
						setcolor(15);
						outtextxy(Left+10,Top+30,"incorrect file name or file does not exist.");
						outtextxy(Left+10,Top+40,"press any key to reenter file name or Esc to Cancel");
						outtextxy(Left+10,Top+90,"Esc-Exit");
						choice=getch();
						if(choice==27)
						{
							break;
						}
					}
				}/*end for(;;)*/
			}/*end of menu if*/
			else if(sta==3)
			{
				int c,ch;
				char UserName1[30],UserName2[30]="";
				int GotName=0,GaveName=0;/*flags*/
				int INBuffer[100],OUTBuffer[100];/*output BUFFERS*/
				int INPtr=0,OUTPtr=0;
				int v=0,flag=0,sl;
				char s;
				int i;
				closegraph();
				clrscr();
				printf("%c",201);
				for(i=1;i<=78;i++)
				{
					printf("%c",205);
				}
					printf("%c%c",187,186);
					gotoxy(29,2);
					printf("COM PORT CHAT UTILITY");
					gotoxy(80,2);
					printf("%c%c",186,200);
					for(i=1;i<=78;i++)
					{
						printf("%c",(205));
					}
					printf("%c",(188));
					i=0;
					printf("\nenter your name :");
					scanf("%s",&UserName1);
					sl=strlen(UserName1);
					do
					{
						if(GotName && GaveName)
						{
							if(!flag)
							{
								printf("\n%s:",UserName1);
								flag=1;
							}
							c=inportb(PORT1+5);/*check to see if char has been recieved.*/
							if(c & 1)
							{
								ch=inportb(PORT1);/*IF SO ,then get char*/
								if(ch==13)
								{
									printf("\n%s:",UserName2);
									for(i=0;i<INPtr-1;i++)
									{
										printf("%c",(INBuffer[i]));
									}
									INPtr=0;
									printf("\n%s:",UserName1);
								}/*end of our data,as we got the name.*/
								else
								{
									INBuffer[INPtr]=ch;
									INPtr++;
								}
							}/*&c*/
						}/*G&G*/
						if(kbhit())
						{
							ch=getch();/*if key pressed,get char*/
							if((ch == 13) && GaveName && GotName)
							{
								for(i=0;i<=OUTPtr;i++)
								{
									outportb(PORT1,OUTBuffer[i]);
									delay(1);
								}
								outportb(PORT1,13);
								printf("\n%s:",UserName1);
								OUTPtr=0;
							}
							else if(GaveName && GotName)
							{
								OUTBuffer[OUTPtr]=ch;
								OUTPtr++;
								printf("%c",ch);
							}
						}
						if(!GotName)/*we want the name of the user on other computer*/
						{
							c=inportb(PORT1+5);/*check to see if char has been recieved.*/
							if(c&1)
							{
								ch=inportb(PORT1);/*IF SO THE GET CHAR*/
								if(ch==13)
								{
									i=0;
									printf("\n user on remote computer:%s",UserName2);
									printf("\n press Esc to Exit");
									GotName=1;
								}/*end of our data, as we got the name*/
								else
								{
									s=ch;
									UserName2[i]=s;/*store name*/
									i++;
								}
							}
						}/*end of got name*/
						if(!GaveName)
						{
							outportb(PORT1,UserName1[v]);/*send name char by char*/
							v++;
							if(v == sl)
							{
								outportb(PORT1,13);
								GaveName=1;
							}
						}
					}while(ch!=27);/*Quit when Esc(ASC27) is pressed*/
				}
				closegraph();/*end of chat part*/
				}
Esempio n. 26
0
void Script::EvaluateLine(String & line)
{
	/// Default line processed once?
	lineProcessed = true;

	line.SetComparisonMode(String::NOT_CASE_SENSITIVE);
	// "80Gray50Alpha.png"
#define DEFAULT_TEXTURE_SOURCE	"black50Alpha.png"
#define DEFAULT_TEXT_SIZE_RATIO	0.3f
	
	/// Some state began, take not of it?
	if (line.Contains("Wait("))
	{
		WaitScript * wait = new WaitScript(line, this);
		wait->SetDeleteOnEnd(true);
		ScriptMan.PlayScript(wait);
	}
	else if (line.StartsWith("Key:"))
	{
		String keyStr = line.Tokenize(":")[1];
		keyStr.RemoveSurroundingWhitespaces();
		int keyCode = GetKeyForString(keyStr);
		assert(keyCode != 0);
		InputMan.KeyDown(MainWindow(), keyCode, false);
		InputMan.KeyUp(MainWindow(), keyCode);
		lineFinished = true;
	}
	else if (line.Contains("PlayScript("))
	{
		List<String> tokens = line.Tokenize("(),");
		// Source of script within the parenthesis.
		String source = tokens[1];
		bool wait = true;
		Script * scriptParent = this;
		if (tokens.Size() >= 3)
		{
			wait = tokens[2].ParseBool();
			if (!wait)
			{
				scriptParent = NULL;
				this->lineFinished = true;
			}
		}
		Script * script = new Script(source, scriptParent);
		script->source = source;
		bool loaded = script->Load();
		assert(loaded);
		ScriptMan.PlayScript(script);
	}
	else if (line == "DisableActiveUI")
	{
		InputMan.DisableActiveUI();
		lineFinished = true;
		uiDisabled = true;
	}
	else if (line == "EnableActiveUI")
	{
		InputMan.EnableActiveUI();
		lineFinished = true;
	}
	else if (line.Contains("PreloadTexturesInDirectory("))
	{
		// Fetch the stuff, do the buff
		String dir = line.Tokenize("()")[1];
		List<String> files;
		int num = GetFilesInDirectory(dir, files);
		for (int i = 0; i < files.Size(); ++i)
		{
			String path = dir + "/" + files[i];
			Texture * tex = TexMan.LoadTexture(path);
			Graphics.QueueMessage(new GMBufferTexture(tex));
		}
		lineFinished = true;
	}
	else if (line.Contains("Begin("))
	{
		String stateBeginning = line.Tokenize("()")[1];
		if (stateBeginning == "Cutscene")
		{
			BeginCutscene();
		}
		lineFinished = true;
	}
	else if (line.Contains("End("))
	{
		String stateEnding = line.Tokenize("()")[1];
		if (stateEnding == "Cutscene")
		{
			EndCutscene();
		}
		lineFinished = true;
	}
	else if (line.Contains("EndScript"))
	{
		// End it.
		scriptState = ENDING;
	}
	else if (line.Contains("EnterGameState("))
	{
		String name = line.Tokenize("()")[1];		
		StateChanger * changer = new StateChanger(line, this);
		ScriptMan.PlayScript(changer);
	}
	else if (line.Contains("FadeTo(") || line.Contains("FadeIn("))
	{
		FadeInEffect * fade = new FadeInEffect(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeInBackground("))
	{
		FadeInBackground * fade = new FadeInBackground(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeOutBackground("))
	{
		FadeOutBackground * fade = new FadeOutBackground(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeOut"))
	{
		FadeOutEffect * fade = new FadeOutEffect(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeText("))
	{
		FadeTextEffect * text = new FadeTextEffect(line, this);
		ScriptMan.PlayScript(text);
		lineFinished = true;
	}
	else if (line.Contains("PlaySong("))
	{
		// Just play it.
		String song = line.Tokenize("()")[1];
		TrackMan.PlayTrack(song);
		// Line finished straight away.
		lineFinished = true;
	}
	else if (line.Contains("Dialogue")){
		/// If raw string, output it straight away! (should later be queued to some kind of dialogue-manager?)
		if (line.Contains("\"")){
			/// Create dialogue UI and append it to the current UI!
			String text = line.Tokenize("\"")[1];
			std::cout<<"\n"<<text;
			UIButton * dialogue = new UIButton("Dialogue");
			dialogue->exitable = false;
			dialogue->text = text;
			dialogue->activationMessage = "PopFromStack(this)&Remove(this)&ContinueEvent("+this->name+")";
			dialogue->textureSource = DEFAULT_TEXTURE_SOURCE;
			dialogue->textSizeRatio = DEFAULT_TEXT_SIZE_RATIO;
			dialogue->sizeRatioY = 0.3f;
			dialogue->alignmentY = 0.15f;
			dialogue->state |= UIState::DIALOGUE;  // Flag the dialogue-state flag to signify importance!
			Graphics.QueueMessage(new GMAddUI(dialogue, "root"));
			Graphics.QueueMessage(GMPushUI::ToUI("Dialogue", ActiveUI()));
		}
		/// If no quotes, load the specified dialogue-file and begin processing that instead, waiting until it is finished.!
		else {
			/// Give the npc a dialogue?
		//	assert(false);
			// Send it tot he state too, to attach to the appropriate thingymajig.
			Message * message = new Message(line);
			/// Set this event as
			message->scriptOrigin = this;
			MesMan.QueueMessage(message);
			/// Instant thingies.
			lineFinished = true;
		}
	}
	else if (line.Contains("Answer")){
		///  Go to EndAnswers..!
		lineFinished = true;
		for (int i = currentLine; i < lines.Size(); ++i){
			String line = lines[i];
			if (line.Contains("EndAnswers")){
				currentLine = i;
				lineFinished = true;
				return;
			}
		}
		assert(false && "No EndAnswers found? No good, jaow ;___;");
	}
	else if (line.Contains("BeginAlternatives") || line.Contains("BeginQuestion")){
		/// Create dialogue UI and append it to the current UI!
		String text = line.Tokenize("\"")[1];
		std::cout<<"\n"<<text;
		UIElement * dialogue = new UIElement();
		dialogue->exitable = false;
		dialogue->name = "AlternativesDialogue";
	//	dialogue->activationMessage = "Remove(this)&ContinueEvent("+this->name+")";
		dialogue->textureSource = DEFAULT_TEXTURE_SOURCE;
		dialogue->sizeRatioY = 0.3f;
		dialogue->alignmentY = 0.15f;
		dialogue->state |= UIState::DIALOGUE;  // Flag the dialogue-state flag to signify importance!

		UILabel * dialogueText = new UILabel();
		dialogueText->text = text;
		dialogueText->textSizeRatio = DEFAULT_TEXT_SIZE_RATIO;
		dialogueText->sizeRatioX = 0.5f;
		dialogueText->alignmentX = 0.25f;
		dialogue->AddChild(dialogueText);

		UIList * dialogueAnswerList = new UIList();
		dialogueAnswerList->sizeRatioX = 0.5f;
		dialogueAnswerList->alignmentX = 0.75f;
		dialogue->AddChild(dialogueAnswerList);

		int answers = 0;
		List<UIElement*> answerList;
		// Parse and add answers
		for (int i = currentLine+1; i < lines.Size(); ++i){
			String l = lines[i];
			l.SetComparisonMode(String::NOT_CASE_SENSITIVE);
			List<String> tokens = l.Tokenize(" ");
			String token1 = tokens[0];
			token1.SetComparisonMode(String::NOT_CASE_SENSITIVE);

			if (token1 == "text"){
				l.Remove(token1);
				dialogueText->text = l;
				dialogueText->text.RemoveInitialWhitespaces();
				dialogueText->text.Remove("\"");
				dialogueText->text.Remove("\"");
			}
			else if (l.Contains("Answer")){
				++answers;
				UIButton * answerButton = new UIButton();
				answerButton->name = token1;
				l.Remove("Answer");
				l.RemoveInitialWhitespaces();
				l.Remove("\"");
				l.Remove("\"");
				answerButton->textureSource = DEFAULT_TEXTURE_SOURCE;
				answerButton->text = l;
				answerButton->sizeRatioY = 0.2f;
				answerButton->activationMessage = "ActivateDialogueAlternative("+name+","+answerButton->name+")&PopFromStack("+dialogue->name+")&Remove("+dialogue->name+")";
				answerList.Add(answerButton);
			}
			else if (l.Contains("EndAlternatives")){
				// Donelir. o-o
				break;
			}
			else {
				assert(false && "Bad line! Should only be Answer before EndAlternatives!");
			}
		}
		assert(answers);
		float sizeRatioY = 0.95f / answers;
		for (int i = 0; i < answers; ++i){
			UIElement * ans = answerList[i];
		//	ans->sizeRatioY = sizeRatioY; // Stupid to set the sizeRatioY to be this dynamic, yo.
			dialogueAnswerList->AddChild(ans);
		}
		isInAlternativeDialogue = true;
		Graphics.QueueMessage(new GMAddUI(dialogue, "root"));
		Graphics.QueueMessage(GMPushUI::ToUI(dialogue, ActiveUI()));
	}
	else if (line.Contains("elsif") || line.Contains("elseif") || line.Contains("else if"))
	{
		/// Should be in an if-stack, check if we already evaluated.
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		/// If already evaluated, jump to endif.
		if (sl.evaluatedAtLine > 0)
		{
			// Jump to endif.
			JumpToEndif();
			return;
		}
		/// If not, handle the conditional first.
		HandleConditional(line);
	}
	else if (line.Contains("if(") || line.Contains("if ("))
	{
		// Add to stack.
		stack.AddItem(ScriptLevel(ScriptLevel::IF_CLAUSE, currentLine));
		HandleConditional(line);
	}
	else if (line.Contains("else"))
	{
//		if (ifProcessed)
		//	JumpToEndif();
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		if (sl.evaluatedAtLine > 0)
		{
			JumpToEndif();
			return;
		}
		lineFinished = true;
		return;
	}
	else if (line.Contains("endif"))
	{
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		stack.RemoveLast();
		lineFinished = true;
	}
	else if (line.Contains("endwhile"))
	{
		// Go to start!
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::WHILE_LOOP);
		currentLine = sl.evaluatedAtLine;
		String startLine = lines[currentLine];
		HandleConditional(startLine);
//		lineFinished = true;
		// Evaluate?
//		stack.RemoveLast();
	}
	else if (line.Contains("while"))
	{
		stack.AddItem(ScriptLevel(ScriptLevel::WHILE_LOOP, currentLine));
		HandleConditional(line);
	}
/*	else if (line.Contains("CreateInt")){
		List<String> tokens = line.Tokenize(" \t");
		String varName = tokens[1];
		int initialValue = 0;
		if (tokens.Size() >= 3)
			initialValue = tokens[2].ParseInt();
		if (!GameVars.Get(varName)){
			GameVars.CreateInt(varName, initialValue);
		}
		lineFinished = true;
	}
	/*
	else if (line.Contains("SetInt ")){
		List<String> tokens = line.Tokenize(" \t");
		String varName = tokens[1];
		int value = tokens[2].ParseInt();
		GameVars.SetInt(varName, value);
		lineFinished = true;
	}*/
	else if (line.Contains("Repeatable")){
		/// Flag the event as repeatable.
		repeatable = true;
		lineFinished = true;
	}
	// Consider just making an else-clause for all remaining events to be processed by the specific game instead?
	else if (
		line.Contains("SpawnEntity") ||
		line.Contains("OnApproach") ||
		line.Contains("OnInteract") ||
		line.Contains("DisableMovement") ||
		line.Contains("EnableMovement") ||
		line.Contains("Zone(") ||
		line.Contains("PlacePlayer(") ||
		line.Contains("TrackPlayer")
		)
	{
		Message * message = new Message(line);
		/// Set this event as
		message->scriptOrigin = this;
		MesMan.QueueMessage(message);
		/// Instant thingies.
		lineFinished = true;
	}
	else {
		/// Try evaluate it as an expression.
		Expression exp;
		List<Variable> allVars = GameVars.GetAllExpressionVariables() + variables;
		exp.functionEvaluators = functionEvaluators; // Set evaluators.
		bool parseOK = exp.ParseExpression(line);
		if (line.Contains("SetMovementPattern"))
			int p = 4;;
		if (parseOK)
		{
			ExpressionResult res = exp.Evaluate(allVars);
			/// Continue until it returns true! o.o
			if (res.type != DataType::NO_TYPE)
			{
				if (res.GetBool() == true)
				{
					lineFinished = true;
					return;
				}
			}
		}


//		std::cout<<"\nUndefined event command: "<<line;
//		std::cout<<"\nPassing it as a custom command to the game states for further processing.";
		Message * message = new Message(line);
		/// Set this event as source of it.
		message->scriptOrigin = this;
		MesMan.QueueMessage(message);
		lineFinished = true;
	//	assert(false && "Undefined event command!");
	};
}
Esempio n. 27
0
int main(int argc, char** argv)
{

  Q_INIT_RESOURCE(resource);

  QString nextTranslator;


  //const char* argv_2[]={"OpenBrf"}; int argc_2=1;

  //QApplication app(argc_2,argv_2); //argc, argv);
  QApplication app(argc, argv);
  QStringList arguments = QCoreApplication::arguments();
  app.setApplicationVersion(applVersion);
  app.setApplicationName("OpenBrf");
  app.setOrganizationName("Marco Tarini");
  app.setOrganizationDomain("Marco Tarini");


  bool useAlphaC = false;

  if ((arguments.size()>1)&&(arguments[1].startsWith("-"))) {
    if ((arguments[1] == "--dump")&&(arguments.size()==4)) {
      switch (MainWindow().loadModAndDump(arguments[2],arguments[3])) {
      case -1: printf("OpenBRF: invalid module folder\n"); break;
      case -2: printf("OpenBRF: error scanning brf data or ini file\n"); break;
      case -3: printf("OpenBRF: error writing output file\n"); break;
      default: return 0;
      }
      return -1;
    } else if ((arguments[1] == "--useAlphaCommands")&&(arguments.size()==2))  {
      useAlphaC = true;
      arguments.clear();
    } else {
      showUsage();
      return -1;
    }

  }

  while (1){
    QTranslator translator;
    QTranslator qtTranslator;

    if (nextTranslator.isEmpty()){
      QString loc;
      switch (MainWindow::getLanguageOption()) {
      default: loc = QLocale::system().name(); break;
      case 1: loc = QString("en");break;
      case 2: loc = QString("zh_CN");break;
      case 3: loc = QString("es");break;
      case 4: loc = QString("de");break;
      }
      translator.load(QString(":/translations/openbrf_%1.qm").arg(loc));

      qtTranslator.load(QString(":/translations/qt_%1.qm").arg(loc));
    } else {
      translator.load(nextTranslator);
    }
    app.installTranslator(&translator);
    app.installTranslator(&qtTranslator);

    MainWindow w;
    w.setUseAlphaCommands(useAlphaC);
    w.show();

    if (arguments.size()>1) w.loadFile(arguments[1]); arguments.clear();
    if (app.exec()==101) {
      nextTranslator = w.getNextTranslatorFilename();
      continue; // just changed language! another run
    }
    break;
  }

  return 0;
}
Esempio n. 28
0
/*----------------------------------------------------------------------------------------------
	Handle notifications.

	@param ctid Identifier of the common control sending the message.
	@param pnmh Pointer to an NMHDR structure containing notification code and additional info.
	@param lnRet Value to be returned to system windows send message call.

	@return True if the notification has been handled, otherwise false.
----------------------------------------------------------------------------------------------*/
bool TssEdit::OnNotifyChild(int id, NMHDR * pnmh, long & lnRet)
{
	AssertPtr(pnmh);
	if (SuperClass::OnNotifyChild(id, pnmh, lnRet))
		return true;

	bool fToolTip = HasToolTip();

	HWND hwndParent = ::GetParent(m_hwnd);

	if (fToolTip && pnmh->code == TTN_POP)
	{
		// Wait 1/2 second after the tooltip disappears before resetting the text on the
		// status bar.
		::SetTimer(hwndParent, knToolTipTimer, 500, NULL);
		return true;
	}
	else if (fToolTip && pnmh->code == TTN_SHOW)
	{
		// This flag keeps the tooltip from recursively appearing and crashing the program.
		static bool s_fIgnore = false;
		if (!s_fIgnore)
		{
			// If another tooltip shows up in the 1/2 second time interval set above, cancel
			// the timer, so the status bar doesn't get changed back to the idle string.
			::KillTimer(hwndParent, knToolTipTimer);

			// Create a new notification message and forward it to the parent in order to get
			// the default response for a normal tooltip (which is currently defined in
			// AfMainWnd::OnNotifyChild).
			NMTTDISPINFO nmtdi;
			nmtdi.hdr.hwndFrom = (HWND)id;
			nmtdi.hdr.code = TTN_GETDISPINFO;
			nmtdi.hdr.idFrom = ::GetDlgCtrlID((HWND)id);
			*nmtdi.szText = 0;
			::SendMessage(::GetParent(m_hwnd), WM_NOTIFY, nmtdi.hdr.idFrom, (LPARAM)&nmtdi);

			// Update the status bar here rather than above after ::KillTimer() so that the
			// string for the new command is already set.
			AfMainWnd * pafw = MainWindow();
			AssertPtr(pafw);
			AfStatusBar * pstat = pafw->GetStatusBarWnd();
			if (pstat)
				pstat->DisplayHelpText();

			if (*nmtdi.szText)
			{
				// Now we have the text for the control, so update the text in the tooltip.
				TOOLINFO ti = { isizeof(ti) };
				ti.hwnd = (HWND)id;
				ti.uId = (uint)ti.hwnd;
				ti.lpszText = nmtdi.szText;
				::SendMessage(pnmh->hwndFrom, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti);

				// This is required so the tooltip gets resized properly.
				s_fIgnore = true;
				::SendMessage(pnmh->hwndFrom, TTM_UPDATE, 0, 0);
				s_fIgnore = false;
				return true;
			}
		}
	}

	return false;
}
Esempio n. 29
0
void Application::InitGraphics()
{
	D3DDevice::Create(MainWindow()->GetHWnd(), mWidth, mHeight);
}
Esempio n. 30
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);
	}
}