// Return file contents as an array of lines. Assume file is UTF-8 encoded text. // // lines = readFileLines(filename); // filename: VFS filename (may include path) CScriptVal JSI_VFS::ReadFileLines(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename) { // // read file // CVFSFile file; if (file.Load(g_VFS, filename) != PSRETURN_OK) return JSVAL_NULL; CStr contents = file.DecodeUTF8(); // assume it's UTF-8 // Fix CRLF line endings. (This function will only ever be used on text files.) contents.Replace("\r\n", "\n"); // // split into array of strings (one per line) // std::stringstream ss(contents); JSContext* cx = pCxPrivate->pScriptInterface->GetContext(); JSObject* line_array = JS_NewArrayObject(cx, 0, NULL); std::string line; int cur_line = 0; while (std::getline(ss, line)) { // Decode each line as UTF-8 JS::RootedValue val(cx); ScriptInterface::ToJSVal(cx, val.get(), CStr(line).FromUTF8()); JS_SetElement(cx, line_array, cur_line++, val.address()); } return OBJECT_TO_JSVAL( line_array ); }
// Return file contents as an array of lines. Assume file is UTF-8 encoded text. // // lines = readFileLines(filename); // filename: VFS filename (may include path) JS::Value JSI_VFS::ReadFileLines(ScriptInterface::CxPrivate* pCxPrivate, const std::wstring& filename) { JSContext* cx = pCxPrivate->pScriptInterface->GetContext(); JSAutoRequest rq(cx); // // read file // CVFSFile file; if (file.Load(g_VFS, filename) != PSRETURN_OK) return JSVAL_NULL; CStr contents = file.DecodeUTF8(); // assume it's UTF-8 // Fix CRLF line endings. (This function will only ever be used on text files.) contents.Replace("\r\n", "\n"); // // split into array of strings (one per line) // std::stringstream ss(contents); JS::RootedObject line_array(cx, JS_NewArrayObject(cx, JS::HandleValueArray::empty())); std::string line; int cur_line = 0; while (std::getline(ss, line)) { // Decode each line as UTF-8 JS::RootedValue val(cx); ScriptInterface::ToJSVal(cx, &val, CStr(line).FromUTF8()); JS_SetElement(cx, line_array, cur_line++, val); } return JS::ObjectValue(*line_array); }
virtual void Reload() { Unload(); CVFSFile vertexFile; if (vertexFile.Load(g_VFS, m_VertexFile) != PSRETURN_OK) return; CVFSFile fragmentFile; if (fragmentFile.Load(g_VFS, m_FragmentFile) != PSRETURN_OK) return; CPreprocessorWrapper preprocessor; preprocessor.AddDefines(m_Defines); #if CONFIG2_GLES // GLES defines the macro "GL_ES" in its GLSL preprocessor, // but since we run our own preprocessor first, we need to explicitly // define it here preprocessor.AddDefine("GL_ES", "1"); #endif CStr vertexCode = preprocessor.Preprocess(vertexFile.GetAsString()); CStr fragmentCode = preprocessor.Preprocess(fragmentFile.GetAsString()); #if CONFIG2_GLES // Ugly hack to replace desktop GLSL 1.10/1.20 with GLSL ES 1.00, // and also to set default float precision for fragment shaders vertexCode.Replace("#version 110\n", "#version 100\n"); vertexCode.Replace("#version 110\r\n", "#version 100\n"); vertexCode.Replace("#version 120\n", "#version 100\n"); vertexCode.Replace("#version 120\r\n", "#version 100\n"); fragmentCode.Replace("#version 110\n", "#version 100\nprecision mediump float;\n"); fragmentCode.Replace("#version 110\r\n", "#version 100\nprecision mediump float;\n"); fragmentCode.Replace("#version 120\n", "#version 100\nprecision mediump float;\n"); fragmentCode.Replace("#version 120\r\n", "#version 100\nprecision mediump float;\n"); #endif if (!Compile(m_VertexShader, m_VertexFile, vertexCode)) return; if (!Compile(m_FragmentShader, m_FragmentFile, fragmentCode)) return; if (!Link()) return; m_IsValid = true; }
// Return file contents in a string. Assume file is UTF-8 encoded text. // // contents = readFile(filename); // filename: VFS filename (may include path) CScriptVal JSI_VFS::ReadFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename) { CVFSFile file; if (file.Load(g_VFS, filename) != PSRETURN_OK) return JSVAL_NULL; CStr contents = file.DecodeUTF8(); // assume it's UTF-8 // Fix CRLF line endings. (This function will only ever be used on text files.) contents.Replace("\r\n", "\n"); // Decode as UTF-8 return ScriptInterface::ToJSVal( pCxPrivate->pScriptInterface->GetContext(), contents.FromUTF8() ); }
//------------------------------------------------------------------------------ /// \brief Reads Line 2a. WELLID,NNODES //------------------------------------------------------------------------------ void ProcessorMNW2::impl::ReadLn2a (std::fstream& a_is, std::fstream& a_os) { std::string line; std::getline(a_is, line); a_os << line << "\n"; CStr str = line.c_str(); str.Replace('\'', '\"'); EReadAsciiFile e; e.UseExceptions(); e.SetLine((LPCTSTR)str); Mnw2Well w; e.ReadData(w.m_WELLID); e.ReadData(w.m_NNODES); m_wells.push_back(w); } // ProcessorMNW2::impl::ReadLn2a
// Return file contents in a string. Assume file is UTF-8 encoded text. // // contents = readFile(filename); // filename: VFS filename (may include path) JS::Value JSI_VFS::ReadFile(ScriptInterface::CxPrivate* pCxPrivate, const std::wstring& filename) { JSContext* cx = pCxPrivate->pScriptInterface->GetContext(); JSAutoRequest rq(cx); CVFSFile file; if (file.Load(g_VFS, filename) != PSRETURN_OK) return JS::NullValue(); CStr contents = file.DecodeUTF8(); // assume it's UTF-8 // Fix CRLF line endings. (This function will only ever be used on text files.) contents.Replace("\r\n", "\n"); // Decode as UTF-8 JS::RootedValue ret(cx); ScriptInterface::ToJSVal(cx, &ret, contents.FromUTF8()); return ret; }
BOOL CMortScriptApp::InitInstance() { SetRegistryKey( L"Mort" ); CParseCmdLine myCmdLine; myCmdLine.ParseCmdLine( m_lpCmdLine ); TCHAR exe[MAX_PATH]; ::GetModuleFileName(NULL,exe,MAX_PATH); ExecuteFileName = exe; CStr file = myCmdLine.Filename; // m_lpCmdLine; // file.TrimLeft( '\"' ); file.TrimRight( '\"' ); if ( myCmdLine.RegOnly || file.IsEmpty() ) { RegisterFileClass(); RegisterFileType( L".jscr", L"JScripts" ); RegisterFileType( L".mscr", L"JScripts" ); if ( !myCmdLine.RegOnly ) { MessageBox( NULL , L".jscr and .mscr extensions registered.\nPlease run any .jscr/.mscr file or read the manual.\n\n" L"(c) Mirko Schenk 2005-2007" , L"JScripts V" + CStr( VERSION_INFO ) , MB_OK|MB_SETFOREGROUND ); } } else { if ( file.GetLength() >= 4 /* file.GetLength() >= 8 && file.Right(8).CompareNoCase( L".mortrun" ) == 0 || file.GetLength() >= 5 && file.Right(5).CompareNoCase( L".mscr" ) == 0 */ ) { CStr mutexName = file; mutexName.MakeLower(); #ifdef DESKTOP // Windows XP doesn't like some path characters in the mutex' name mutexName.Replace( ':', '_' ); mutexName.Replace( '\\', '/' ); #endif MutexName = (LPCTSTR)mutexName; HANDLE mutex = ::CreateMutex(NULL, FALSE, MutexName); if ( mutex!=NULL ) { int exists = ::GetLastError(); if ( exists == ERROR_ALREADY_EXISTS) { DWORD procId = GetRunningScriptProcId( file ); if ( procId != NULL ) { /* CString msg; msg.Format( L"Process ID: %08x", procId ); MessageBox( NULL, msg, L"Debug", MB_SETFOREGROUND ); */ FindAppT findApp; findApp.procId = procId; findApp.hWnd = NULL; ::EnumWindows( FindApplicationWindowProc, (LPARAM)&findApp ); if ( findApp.hWnd != NULL ) { // msg.Format( L"Set foreground window: %08x", findApp.hWnd ); // MessageBox( NULL, msg, L"Debug", MB_SETFOREGROUND ); ::SetForegroundWindow( findApp.hWnd ); } } else exists = 0; //MessageBox( NULL, L"Process opened", L"Debug", MB_SETFOREGROUND ); /* TCHAR procName[256]; ::GetModuleFileName((HMODULE)procId,procName,256); //MessageBox( NULL, procName, L"Debug", MB_SETFOREGROUND ); if ( CString(procName).Right(14).CompareNoCase( L"MortScript.exe" ) == 0 ) { int aw = MessageBox( NULL , L"Script seems to be running. Cancel old script?" , L"Script already running" , MB_YESNO|MB_SETFOREGROUND ); if ( aw == IDYES ) { RegWriteDW( HKEY_CURRENT_USER, L"Software\\JScripts\\Abort", MutexName, 1 ); DWORD exitCode = 0; SetCursor(LoadStandardCursor(IDC_WAIT)); for ( int i=0; i<=10; i++ ) { Sleep(1000); if ( GetExitCodeProcess( hProc, &exitCode ) == FALSE ) { //MessageBox( NULL, L"GetExitCode failed", L"Debug", MB_SETFOREGROUND ); exitCode = 0; break; } else { if ( exitCode != STILL_ACTIVE ) { //MessageBox( NULL, L"No longer active", L"Debug", MB_SETFOREGROUND ); break; } } } SetCursor(LoadStandardCursor(IDC_ARROW)); if ( exitCode == STILL_ACTIVE ) { int aw = MessageBox( NULL , L"Script seems to be hanging or busy. Terminate old script?" , L"Script still running" , MB_YESNO|MB_SETFOREGROUND ); if ( aw == IDYES ) { TerminateProcess( hProc, 0 ); } } } } else { exists = 0; } CloseHandle( hProc ); } else { exists = 0; } */ } if ( exists != ERROR_ALREADY_EXISTS ) { HKEY key; if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, 0, &key ) == ERROR_SUCCESS ) { RegDeleteValue( key, MutexName ); RegCloseKey( key ); } DWORD currProcId = GetCurrentProcessId(); //CString dbg; //dbg.Format(L"ProcId: %d", GetCurrentProcessId()); //MessageBox( NULL, dbg, L"Debug", MB_SETFOREGROUND ); // Remove old script entries with same process id if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, 0, &key ) == ERROR_SUCCESS ) { int idx; TCHAR valName[MAX_PATH]; DWORD valSize = MAX_PATH, type; DWORD value, valueSize = sizeof(DWORD); CStrArray oldProcesses; for ( idx = 0; RegEnumValue( key, idx, valName, &valSize, NULL, &type, (BYTE*)&value, &valueSize ) == ERROR_SUCCESS; idx++ ) { if ( type == REG_DWORD && value == currProcId ) { oldProcesses.Add( valName ); } valSize = MAX_PATH; valueSize = sizeof(DWORD); } for ( idx = 0; idx < oldProcesses.GetSize(); idx++ ) { RegDeleteValue( key, oldProcesses.GetAt(idx) ); } RegCloseKey( key ); } RegWriteDW( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", MutexName, currProcId ); if ( myCmdLine.WaitForFile > 0 && (long)FileOrDirExists( file, 0 ) == 0 ) { CDlgWait wait(NULL); wait.AllowOK = TRUE; wait.Countdown = myCmdLine.WaitForFile; wait.Expression = L"FileExists(\"" + file + L"\")"; wait.Title = L"JScripts"; wait.m_Label = L"Script " + file + " not found, waiting for existance (storage card not initialized?)"; wait.DoModal(); } if ( myCmdLine.WaitForFile <= 0 || (long)FileOrDirExists( file, 0 ) == 1 ) { g_hInst = theApp.m_hInstance; SYSTEMTIME now; GetLocalTime( &now ); long seed = SystemTimeToUnixTime( now ); srand( seed ); AppPath = m_pszHelpFilePath; AppPath = AppPath.Left( AppPath.ReverseFind('\\') ); ScriptAborted = CreateEvent( 0, TRUE, FALSE, CStr(MutexName)+L"ScriptAborted" ); StatusDialog = new CDlgStatus( file ); //status.DoModal(); CInterpreter interpreter; //Debug(file); //jwz:modi interpreter.RunFile( file ); interpreter.Parser(); //jwz:modi end if ( StatusWindow != NULL ) { StatusDialog->ScriptFinished = TRUE; SendMessage( StatusWindow, WM_EXIT_STATUS, 0, 0 ); WaitForSingleObject( StatusDialogFinished, INFINITE ); CloseHandle( StatusDialogFinished ); } delete StatusDialog; UnloadToolhelp(); CloseHandle( ScriptAborted ); ReleaseMutex( mutex ); Variables.RemoveAll(); for ( int i = 0; i<LocalVariablesStack.GetSize(); i++ ) delete (CMapStrToValue*)LocalVariablesStack.GetAt(i); POSITION pos = FileHandles.GetStartPosition(); CStr key; void *value; while ( pos != 0 ) { FileHandles.GetNextAssoc( pos, key, value ); if ( value != NULL ) { delete (CFileInfo*)value; } } FileHandles.RemoveAll(); if ( ChoiceFont != NULL ) DeleteObject( ChoiceFont ); if ( StatusListFont != NULL ) DeleteObject( StatusListFont ); } if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, KEY_WRITE, &key ) == ERROR_SUCCESS ) { RegDeleteValue( key, MutexName ); RegCloseKey( key ); } } CloseHandle( mutex ); } else { int error = ::GetLastError(); MessageBox( NULL , L"Error creating mutex" , L"JScripts" , MB_OK|MB_SETFOREGROUND ); } } else { MessageBox( NULL , L"Invalid file type for MortScript" , L"JScripts" , MB_OK|MB_SETFOREGROUND ); } } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
void CGUI::Xeromyces_ReadObject(XMBElement Element, CXeromyces* pFile, IGUIObject *pParent, const std::vector<std::pair<CStr, CStr> >& NameSubst, boost::unordered_set<VfsPath>& Paths) { ENSURE(pParent); int i; // Our object we are going to create IGUIObject *object = NULL; XMBAttributeList attributes = Element.GetAttributes(); // Well first of all we need to determine the type CStr type (attributes.GetNamedItem(pFile->GetAttributeID("type"))); if (type.empty()) type = "empty"; // Construct object from specified type // henceforth, we need to do a rollback before aborting. // i.e. releasing this object object = ConstructObject(type); if (!object) { // Report error that object was unsuccessfully loaded LOGERROR(L"GUI: Unrecognized object type \"%hs\"", type.c_str()); return; } // Cache some IDs for element attribute names, to avoid string comparisons #define ELMT(x) int elmt_##x = pFile->GetElementID(#x) #define ATTR(x) int attr_##x = pFile->GetAttributeID(#x) ELMT(object); ELMT(action); ELMT(repeat); ATTR(style); ATTR(type); ATTR(name); ATTR(hotkey); ATTR(z); ATTR(on); ATTR(file); // // Read Style and set defaults // // If the setting "style" is set, try loading that setting. // // Always load default (if it's available) first! // CStr argStyle (attributes.GetNamedItem(attr_style)); if (m_Styles.count("default") == 1) object->LoadStyle(*this, "default"); if (! argStyle.empty()) { // additional check if (m_Styles.count(argStyle) == 0) { LOGERROR(L"GUI: Trying to use style '%hs' that doesn't exist.", argStyle.c_str()); } else object->LoadStyle(*this, argStyle); } // // Read Attributes // bool NameSet = false; bool ManuallySetZ = false; // if z has been manually set, this turn true CStr hotkeyTag; // Now we can iterate all attributes and store for (i=0; i<attributes.Count; ++i) { XMBAttribute attr = attributes.Item(i); // If value is "null", then it is equivalent as never being entered if (CStr(attr.Value) == "null") continue; // Ignore "type" and "style", we've already checked it if (attr.Name == attr_type || attr.Name == attr_style) continue; // Also the name needs some special attention if (attr.Name == attr_name) { CStr name (attr.Value); // Apply the requested substitutions for (size_t j = 0; j < NameSubst.size(); ++j) name.Replace(NameSubst[j].first, NameSubst[j].second); object->SetName(name); NameSet = true; continue; } // Wire up the hotkey tag, if it has one if (attr.Name == attr_hotkey) hotkeyTag = attr.Value; if (attr.Name == attr_z) ManuallySetZ = true; // Try setting the value if (object->SetSetting(pFile->GetAttributeString(attr.Name), attr.Value.FromUTF8(), true) != PSRETURN_OK) { LOGERROR(L"GUI: (object: %hs) Can't set \"%hs\" to \"%ls\"", object->GetPresentableName().c_str(), pFile->GetAttributeString(attr.Name).c_str(), attr.Value.FromUTF8().c_str()); // This is not a fatal error } } // Check if name isn't set, generate an internal name in that case. if (!NameSet) { object->SetName("__internal(" + CStr::FromInt(m_InternalNameNumber) + ")"); ++m_InternalNameNumber; } // Attempt to register the hotkey tag, if one was provided if (! hotkeyTag.empty()) m_HotkeyObjects[hotkeyTag].push_back(object); CStrW caption (Element.GetText().FromUTF8()); if (! caption.empty()) { // Set the setting caption to this object->SetSetting("caption", caption, true); // There is no harm if the object didn't have a "caption" } // // Read Children // // Iterate children XMBElementList children = Element.GetChildNodes(); for (i=0; i<children.Count; ++i) { // Get node XMBElement child = children.Item(i); // Check what name the elements got int element_name = child.GetNodeName(); if (element_name == elmt_object) { // Call this function on the child Xeromyces_ReadObject(child, pFile, object, NameSubst, Paths); } else if (element_name == elmt_action) { // Scripted <action> element // Check for a 'file' parameter CStrW filename (child.GetAttributes().GetNamedItem(attr_file).FromUTF8()); CStr code; // If there is a file, open it and use it as the code if (! filename.empty()) { Paths.insert(filename); CVFSFile scriptfile; if (scriptfile.Load(g_VFS, filename) != PSRETURN_OK) { LOGERROR(L"Error opening GUI script action file '%ls'", filename.c_str()); throw PSERROR_GUI_JSOpenFailed(); } code = scriptfile.DecodeUTF8(); // assume it's UTF-8 } // Read the inline code (concatenating to the file code, if both are specified) code += CStr(child.GetText()); CStr action = CStr(child.GetAttributes().GetNamedItem(attr_on)); // We need to set the GUI this object belongs to because RegisterScriptHandler requires an associated GUI. object->SetGUI(this); object->RegisterScriptHandler(action.LowerCase(), code, this); } else if (element_name == elmt_repeat) { Xeromyces_ReadRepeat(child, pFile, object, Paths); } else { // Try making the object read the tag. if (!object->HandleAdditionalChildren(child, pFile)) { LOGERROR(L"GUI: (object: %hs) Reading unknown children for its type", object->GetPresentableName().c_str()); } } } // // Check if Z wasn't manually set // if (!ManuallySetZ) { // Set it automatically to 10 plus its parents bool absolute; GUI<bool>::GetSetting(object, "absolute", absolute); // If the object is absolute, we'll have to get the parent's Z buffered, // and add to that! if (absolute) { GUI<float>::SetSetting(object, "z", pParent->GetBufferedZ() + 10.f, true); } else // If the object is relative, then we'll just store Z as "10" { GUI<float>::SetSetting(object, "z", 10.f, true); } } // // Input Child // try { if (pParent == m_BaseObject) AddObject(object); else pParent->AddChild(object); } catch (PSERROR_GUI& e) { LOGERROR(L"GUI error: %hs", e.what()); } }