Handle<Value> ScriptSystem::ExecuteJS(const std::string& code, const std::string& path) { // Init JavaScript context HandleScope handle_scope; Context::Scope context_scope(GetGlobalContext()); // We're just about to compile the script; set up an error handler to // catch any exceptions the script might throw. TryCatch try_catch; // Compile the source code. Local<Script> compiled_script = Script::Compile(ToJSString(code), ToJSString(path)); // if an exception occured if(try_catch.HasCaught()) { ReportException(&try_catch); // return try_catch; } // Run the script! Local<Value> ret = compiled_script->Run(); if(try_catch.HasCaught()) { ReportException(&try_catch); // return try_catch; } FetchGlobalTickFunction(); return handle_scope.Close(ret); }
// Executes a str within the current v8 context. static v8::Local<v8::Value> ExecuteString(Environment* env, v8::Handle<v8::String> source, v8::Handle<v8::String> filename, bool exitOnError = false) { v8::Isolate* isolate = env->isolate(); v8::EscapableHandleScope scope(isolate); v8::TryCatch try_catch; // try_catch must be nonverbose to disable FatalException() handler, // we will handle exceptions ourself. try_catch.SetVerbose(false); v8::Local<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(env, try_catch); if(exitOnError) exit(3); return scope.Escape(v8::Undefined(isolate)->ToObject()); } v8::Local<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(env, try_catch); if(exitOnError) exit(4); return scope.Escape(v8::Undefined(isolate)->ToObject()); } v8::String::Utf8Value str(result); const char* cstr = JSObjectUtils::toCString(str); std::cout << cstr << std::endl << std::flush; return scope.Escape(result); }
// Executes a string within the current v8 context. bool Fragment::Script::ScriptEngine::ExecuteString(v8::Isolate *isolate, v8::Local<v8::String> source, v8::Local<v8::Value> name, bool print_result, bool report_exceptions) { v8::HandleScope handle_scope(isolate); v8::TryCatch try_catch(isolate); v8::ScriptOrigin origin(name); v8::Local<v8::Context> context(isolate->GetCurrentContext()); v8::Local<v8::Script> script; if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) { // Print errors that happened during compilation. if (report_exceptions) ReportException(isolate, &try_catch); return false; } else { v8::Local<v8::Value> result; if (!script->Run(context).ToLocal(&result)) { assert(try_catch.HasCaught()); // Print errors that happened during execution. if (report_exceptions) ReportException(isolate, &try_catch); return false; } else { assert(!try_catch.HasCaught()); if (print_result && !result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::Utf8Value str(result); const char *cstr = ToCString(str); printf("%s\n", cstr); } return true; } } }
bool ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> name, bool print_result, bool report_exceptions) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, name); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions) ReportException(&try_catch); return false; } else { v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { // Print errors that happened during execution. if (report_exceptions) ReportException(&try_catch); return false; } else { if (print_result && !result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::Utf8Value str(result); const char* cstr = ToCString(str); printf("%s\n", cstr); } return true; } } }
bool SMJS_Plugin::RunString(const char* name, const char *source, bool asGlobal){ HandleScope handle_scope(isolate); Context::Scope context_scope(context); TryCatch try_catch; v8::ScriptOrigin origin(String::New(name), v8::Integer::New(0), v8::Integer::New(0)); Handle<Script> script; if(asGlobal){ script = Script::Compile(v8::String::New(source), &origin); }else{ char *buffer = new char[strlen(source) + 100]; strcpy(buffer, "(function(global){"); strcat(buffer, source); strcat(buffer, "})(this);"); script = Script::Compile(v8::String::New(buffer), &origin); delete buffer; } if(script.IsEmpty()) { // Print errors that happened during compilation. ReportException(&try_catch); return false; } else { Handle<Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); return false; } return true; } }
Handle<Object> SorrowContext::SetupInternals(int argc, const char *argv[]) { HandleScope scope; Local<FunctionTemplate> internals_template = FunctionTemplate::New(); internals = Persistent<Object>::New(internals_template->GetFunction()->NewInstance()); Local<Object> global = Context::GetCurrent()->Global(); SET_METHOD(global, "quit", Quit) SET_METHOD(global, "version", Version) SET_METHOD(internals, "compile", CompileScript) if (argc) { Local<Array> lineArgs = Array::New(argc-1); for (int i = 0; i +1 < argc; i++) { lineArgs->Set(Integer::New(i), V8_STR(argv[i+1])); } internals->Set(V8_STR("args"), lineArgs); } else { internals->Set(V8_STR("args"), Array::New()); } Handle<Object> libsObject = Object::New(); LoadNativeLibraries(libsObject); internals->Set(V8_STR("stdlib"), libsObject); Handle<ObjectTemplate> env = ObjectTemplate::New(); env->SetNamedPropertyHandler(EnvGetter); internals->Set(V8_STR("env"), env->NewInstance()); internals->Set(V8_STR("global"), global); binarytypes = new BinaryTypes(internals); iostreams = new IOStreams(internals); Filesystem::Initialize(internals); Extensions::Initialize(internals); TryCatch tryCatch; Local<Value> func = ExecuteString(V8_STR(sorrow_native), V8_STR("sorrow.js")); if (tryCatch.HasCaught()) { ReportException(&tryCatch); exit(10); } ASSERT_PIN(func->IsFunction(), "sorrow.js main function not found"); Local<Function> f = Local<Function>::Cast(func); Local<Value> args[1] = { Local<Value>::New(internals) }; f->Call(global, 1, args); if (tryCatch.HasCaught()) { ReportException(&tryCatch); exit(11); } return internals; } // SetupInternals
void ScriptSystem::Tick(const dtEntity::Message& m) { if(mGlobalTickFunction.IsEmpty()) { return; } HandleScope scope; Context::Scope context_scope(GetGlobalContext()); const dtEntity::TickMessage& msg = static_cast<const dtEntity::TickMessage&>(m); TryCatch try_catch; Handle<Value> argv[3] = { Number::New(msg.GetDeltaSimTime()), Number::New(msg.GetSimulationTime()), Uint32::New(osg::Timer::instance()->time_m()) }; Handle<Value> ret = mGlobalTickFunction->Call(mGlobalTickFunction, 3, argv); if(ret.IsEmpty()) { ReportException(&try_catch); } }
bool HandleUncaughtException(JNIEnv* aEnv) { MOZ_ASSERT(aEnv, "Invalid thread JNI env"); if (!aEnv->ExceptionCheck()) { return false; } #ifdef MOZ_CHECK_JNI aEnv->ExceptionDescribe(); #endif Throwable::LocalRef e = Throwable::LocalRef::Adopt(aEnv, aEnv->ExceptionOccurred()); MOZ_ASSERT(e); aEnv->ExceptionClear(); String::LocalRef stack = java::GeckoAppShell::GetExceptionStackTrace(e); if (stack && ReportException(aEnv, e.Get(), stack.Get())) { return true; } aEnv->ExceptionClear(); java::GeckoAppShell::HandleUncaughtException(e); if (NS_WARN_IF(aEnv->ExceptionCheck())) { aEnv->ExceptionDescribe(); aEnv->ExceptionClear(); } return true; }
JSFiber::scope::~scope() { m_pFiber->m_quit.set(); ReportException(try_catch, m_hr); m_pFiber->holder()->m_fibers.remove(m_pFiber); exlib::Fiber::tlsPut(g_tlsCurrent, 0); }
Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) { HandleScope scope; TryCatch tryCatch; Local<Script> script = Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&tryCatch); exit(1); } Local<Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&tryCatch); exit(1); } return scope.Close(result); } // ExecuteString
bool CPosterProgressDlg::StartJob() { // launch poster rendering engine UINT Threads = m_Main->GetOptionsDlg().GetThreadCount(); if (!m_Engine.LaunchThreads(m_hWnd, Threads)) { ReportError(IDS_CANT_LAUNCH_ENGINE); return(FALSE); } // maybe resume a paused poster CPathStr Path(m_DestPath); Path.RenameExtension(ROW_INDEX_EXT); if (PathFileExists(Path)) { // if paused poster exists in destination folder CMainFrame::CStatusMsg status(IDS_PSTR_RESUMING); CPausedPosterInfo Info; if (!SerializePausedJob(FALSE, Info)) // read paused poster info return(FALSE); // error was already reported if (!m_Engine.ResumePosterJob(Info.m_RowIndex)) { ReportError(IDS_PSTR_CANT_RESUME); return(FALSE); } m_Snap = Info.m_Snap; DeleteFile(Path); // delete row index file } // get bounds and set math precision BigRect Bounds(m_Snap.m_MathPrec, 0, 0); m_Snap.GetBounds(Bounds); // get bounds from snapshot m_Engine.SetMathPrec(m_Snap.m_MathPrec); // set our engine's precision m_Engine.SetPalette(m_Snap.m_Palette, m_Snap.m_Quality, m_Snap.m_CycleLen, m_Snap.m_ColorOffset); // row data file path is same as destination file but different extension CPathStr RowFilePath(m_DestPath); RowFilePath.RenameExtension(ROW_DATA_EXT); // build render info m_RowsDone = 0; m_FrameUID = GetTickCount(); m_FrameSize = CSize(m_Snap.m_ImageSize.cx * m_Snap.m_Antialias, m_Snap.m_ImageSize.cy * m_Snap.m_Antialias); RENDER_INFO ri; ri.FrameBuf = NULL; ri.FractalType = m_Snap.m_FractalType; ri.FrameSize = m_FrameSize; ri.FrameUID = m_FrameUID; ri.Quality = m_Snap.m_Quality; ri.DeepZoom = m_Snap.m_DeepZoom; ri.Exponent = m_Snap.m_Exponent; m_Clock.Reset(); TRY { m_Engine.BeginPosterJob(ri, Bounds, m_Snap, RowFilePath); } CATCH(CFileException, e) { ReportException(e); return(FALSE); }
void JSFiber::callFunction1(v8::Local<v8::Function> func, v8::Local<v8::Value> *args, int argCount, v8::Local<v8::Value> &retVal) { TryCatch try_catch; retVal = func->Call(wrap(), argCount, args); if (try_catch.HasCaught()) { m_error = true; ReportException(try_catch, 0); } }
//授权号不符合 void COperator::OnAuthNoError(TSSmartDoc *pDoc, TSCmdBuffer *pBuffer) { switch(GetMachineType(pDoc)) { case MACHINE_TYPE_5301: ReportException("收集LPort数据时, 返回授权号不符 具体数据为:", pBuffer->pBuffer, pBuffer->pBuffer[3]+7); if( !ModifyRegister(pDoc, pBuffer) ) WriteLog("收集LPort:%d数据时, 返回授权号不符, 修改LPort注册号时出错!", pDoc->m_nAuthID); break; default: break; } }
JSFiber::scope::~scope() { v8::Local<v8::Object> o = m_pFiber->wrap(); m_pFiber->m_quit.set(); m_pFiber->dispose(); s_null->Ref(); o->SetAlignedPointerInInternalField(0, s_null); ReportException(try_catch, m_hr); Isolate::now()->m_fibers.remove(m_pFiber); exlib::Fiber::tlsPut(g_tlsCurrent, 0); }
AutoJSAPI::~AutoJSAPI() { if (mOwnErrorReporting) { ReportException(); // We need to do this _after_ processing the existing exception, because the // JS engine can throw while doing that, and uses this bit to determine what // to do in that case: squelch the exception if the bit is set, otherwise // call the error reporter. Calling WarningOnlyErrorReporter with a // non-warning will assert, so we need to make sure we do the former. JS::ContextOptionsRef(cx()).setAutoJSAPIOwnsErrorReporting(mOldAutoJSAPIOwnsErrorReporting); } if (mOldErrorReporter.isSome()) { JS_SetErrorReporter(JS_GetRuntime(cx()), mOldErrorReporter.value()); } }
void SorrowContext::LoadMain() { HandleScope handle_scope; TryCatch tryCatch; Local<Value> func = internals->Get(String::New("loadMain")); ASSERT_PIN(func->IsFunction(), "loadMain not found"); Local<Function> f = Local<Function>::Cast(func); Local<Object> global = Context::GetCurrent()->Global(); f->Call(global, 0, NULL); if (tryCatch.HasCaught()) { ReportException(&tryCatch); KillPinTool(); } }
void Process() { HandleScope scope; Context::Scope context_scope(mFunction->CreationContext()); Handle<String> loglevel; while(!mMessages.Empty()) { Msg msg = mMessages.Pop(); switch(msg.mLevel) { case dtEntity::LogLevel::LVL_ALWAYS: loglevel = mAlways; break; case dtEntity::LogLevel::LVL_DEBUG: loglevel = mDebug; break; case dtEntity::LogLevel::LVL_ERROR: loglevel = mError; break; case dtEntity::LogLevel::LVL_INFO : loglevel = mInfo; break; case dtEntity::LogLevel::LVL_WARNING: loglevel = mWarning; break; } #if defined (_DEBUG) bool is_debug = true; #else bool is_debug = false; #endif Handle<Value> argv[6] = { loglevel, ToJSString(msg.mFilename), ToJSString(msg.mMethodname), Integer::New(msg.mLinenumber), ToJSString(msg.mMsg), Boolean::New(is_debug) }; TryCatch try_catch; Handle<Value> result = mFunction->Call(mFunction, 6, argv); if(result.IsEmpty()) { ReportException(&try_catch); } } }
void SorrowContext::LoadScript(const char *text, uint32_t size) { HandleScope handle_scope; TryCatch tryCatch; Local<Value> func = internals->Get(String::New("loadScript")); ASSERT_PIN(func->IsFunction(), "loadScript not found"); Local<Function> f = Local<Function>::Cast(func); Local<Object> global = Context::GetCurrent()->Global(); Local<Value> argv[1] = { String::New(text, size) }; f->Call(global, 1, argv); if (tryCatch.HasCaught()) { ReportException(&tryCatch); KillPinTool(); } }
void OnAnimationCompleted(const dtAnim::Animatable& anim) { CallbackMap::iterator iter = mCallbacks.find(&anim); if(iter == mCallbacks.end()) { LOG_ERROR("Callback called but was not registered ?!?"); return; } // only execute once HandleScope scope; TryCatch try_catch; Handle<Value> result = iter->second->Call(iter->second, 0, NULL); mCallbacks.erase(iter); if(result.IsEmpty()) { ReportException(&try_catch); } }
void testProtobufV8(v8::Handle<v8::Context> context) { ALOGD("testProtobufV8 E:"); v8::HandleScope handle_scope; v8::TryCatch try_catch; try_catch.SetVerbose(true); if (try_catch.HasCaught()) { ALOGD("TryCatch.hasCaught is true after protobuf_v8::init"); ReportException(&try_catch); } runJs(context, &try_catch, "local-string", "fileContents = readFileToString('mock_ril.js');\n" "print('fileContents:\\n' + fileContents);\n" "\n" "buffer = readFileToBuffer('ril.desc');\n" "var schema = new Schema(buffer);\n" "\n" "var originalReqEnterSimPin = { pin : 'hello-the-pin' };\n" "print('originalReqEnterSimPin: pin=' + originalReqEnterSimPin.pin);\n" "var ReqEnterSimPinSchema = schema['ril_proto.ReqEnterSimPin'];\n" "serializedOriginalReqEnterSimPin = ReqEnterSimPinSchema.serialize(originalReqEnterSimPin);\n" "print('serializedOriginalReqEnterSimPin.length=' + serializedOriginalReqEnterSimPin.length);\n" "newReqEnterSimPin = ReqEnterSimPinSchema.parse(serializedOriginalReqEnterSimPin);\n" "print('newReqEnterSimPin: pin=' + newReqEnterSimPin.pin);\n" "\n" "var originalReqScreenState = { state : true };\n" "print('originalReqScreenState: state=' + originalReqScreenState.state);\n" "var ReqScreenStateSchema = schema['ril_proto.ReqScreenState'];\n" "var serializedOriginalReqScreenState = ReqScreenStateSchema.serialize(originalReqScreenState);\n" "print('serializedOriginalReqScreenState.length=' + serializedOriginalReqScreenState.length);\n" "var newReqScreenState = ReqScreenStateSchema.parse(serializedOriginalReqScreenState);\n" "print('newReqScreenState: state=' + newReqScreenState.state);\n" "\n" "originalReqScreenState.state = false;\n" "print('originalReqScreenState: state=' + originalReqScreenState.state);\n" "serializedOriginalReqScreenState = ReqScreenStateSchema.serialize(originalReqScreenState);\n" "print('serializedOriginalReqScreenState.length=' + serializedOriginalReqScreenState.length);\n" "newReqScreenState = ReqScreenStateSchema.parse(serializedOriginalReqScreenState);\n" "print('newReqScreenState: state=' + newReqScreenState.state);\n"); ALOGD("testProtobufV8 X"); }
AutoJSAPI::~AutoJSAPI() { if (!mCx) { // No need to do anything here: we never managed to Init, so can't have an // exception on our (nonexistent) JSContext. We also don't need to restore // any state on it. return; } ReportException(); // We need to do this _after_ processing the existing exception, because the // JS engine can throw while doing that, and uses this bit to determine what // to do in that case: squelch the exception if the bit is set, otherwise // call the error reporter. Calling WarningOnlyErrorReporter with a // non-warning will assert, so we need to make sure we do the former. JS::ContextOptionsRef(cx()).setAutoJSAPIOwnsErrorReporting(mOldAutoJSAPIOwnsErrorReporting); if (mOldErrorReporter.isSome()) { JS_SetErrorReporter(JS_GetRuntime(cx()), mOldErrorReporter.value()); } }
Local<Value> ScriptSystem::ExecuteFile(const std::string& path) { HandleScope handle_scope; Handle<Script> script = GetScriptFromFile(path); if(!script.IsEmpty()) { v8::Context::Scope context_scope(GetGlobalContext()); TryCatch try_catch; Local<Value> ret = script->Run(); FetchGlobalTickFunction(); if(try_catch.HasCaught()) { ReportException(&try_catch); return Local<Value>(); } return handle_scope.Close(ret); } return Local<Value>(); }
int callOnRilRequest(v8::Handle<v8::Context> context, int cmd, const void *buffer, RIL_Token t) { DBG("callOnRilRequest E: cmd=%d", cmd); int status; v8::HandleScope handle_scope; v8::TryCatch try_catch; // Get the onRilRequest Function v8::Handle<v8::String> name = v8::String::New("onRilRequest"); v8::Handle<v8::Value> onRilRequestFunctionValue = context->Global()->Get(name); v8::Handle<v8::Function> onRilRequestFunction = v8::Handle<v8::Function>::Cast(onRilRequestFunctionValue); // Create the cmd and token v8::Handle<v8::Value> v8RequestValue = v8::Number::New(cmd); v8::Handle<v8::Value> v8TokenValue = v8::Number::New(int64_t(t)); // Invoke onRilRequest const int argc = 3; v8::Handle<v8::Value> argv[argc] = { v8RequestValue, v8TokenValue, ((Buffer *)buffer)->handle_ }; v8::Handle<v8::Value> result = onRilRequestFunction->Call(context->Global(), argc, argv); if (try_catch.HasCaught()) { ALOGE("callOnRilRequest error"); ReportException(&try_catch); status = STATUS_ERR; } else { v8::String::Utf8Value result_string(result); DBG("callOnRilRequest result=%s", ToCString(result_string)); status = STATUS_OK; } DBG("callOnRilRequest X: status=%d", status); return status; }
Handle<Script> ScriptSystem::GetScriptFromFile(const std::string& path) { std::string code; bool success = GetFileContents(path, code); if(!success) { LOG_ERROR("Could not load script file from " + path); return Handle<Script>(); } HandleScope handle_scope; Context::Scope context_scope(GetGlobalContext()); TryCatch try_catch; Local<Script> compiled_script = Script::Compile(ToJSString(code), ToJSString(path)); if(try_catch.HasCaught()) { ReportException(&try_catch); return Handle<Script>(); } return handle_scope.Close(compiled_script); }
AutoJSAPI::~AutoJSAPI() { if (!mCx) { // No need to do anything here: we never managed to Init, so can't have an // exception on our (nonexistent) JSContext. We also don't need to restore // any state on it. Finally, we never made it to pushing outselves onto the // ScriptSettingsStack, so shouldn't pop. MOZ_ASSERT(ScriptSettingsStack::Top() != this); return; } ReportException(); if (mOldWarningReporter.isSome()) { JS::SetWarningReporter(cx(), mOldWarningReporter.value()); } // Leave the request before popping. if (mIsMainThread) { mAutoRequest.reset(); } ScriptSettingsStack::Pop(this); }
////////////////////////////////////////////////////////////////////////////// // // void ExportGraphicImage( RBitmapImage* pImage, RMBCString *pInitialDir ) // // export a graphic to file from a bitmap image // ////////////////////////////////////////////////////////////////////////////// void ExportGraphicImage( RBitmapImage* pImage, RMBCString *pInitialDir /*=NULL*/) { RImageLibrary rLibrary ; CArray<int, int> arrFileFormats ; // // Build the export file filter list... // CString strFilter, str ; for (int i = 0; i < kNumFormats - 1; i++) { if (rLibrary.IsFormatSupported( (EImageFormat) kImageExportFilters[i][0] )) { str.LoadString( kImageExportFilters[i][1] ) ; strFilter += str ; arrFileFormats.Add( kImageExportFilters[i][0] ) ; } } TpsAssert( kImageExportFilters[i][0] == kImageFormatXRX, "Invalid export format!" ) ; str.LoadString( kImageExportFilters[i][1] ) ; strFilter += str ; strFilter += "|" ; arrFileFormats.Add( kImageExportFilters[i][0] ) ; // // Create and execute the dialog... // RExportGraphicDlg dlg( pImage, strFilter ) ; // Load in the dialog title string CString strTitle ; strTitle.LoadString( STRING_EXPORT_IMAGE_DIALOG_TITLE ) ; dlg.m_ofn.lpstrTitle = (LPCTSTR) strTitle ; if( pInitialDir ) { dlg.m_ofn.lpstrInitialDir = (LPCTSTR)*pInitialDir; } if (IDOK == dlg.DoModal()) { RMBCString strPathName = dlg.GetPathName() ; EImageFormat eFormat = (EImageFormat) arrFileFormats[dlg.m_ofn.nFilterIndex - 1] ; try { if (kImageFormatXRX == eFormat) // exporting as WMF { // get our output image size RRealSize rRealOutputSize( dlg.GetSize() ); RRealSize screenDPI = ::GetScreenDPI(); // create a vector image RVectorImage vectorImage; vectorImage.SetSuggestedWidthInInches( ::PixelsToInches( rRealOutputSize.m_dx, (uLONG) screenDPI.m_dx ) ); vectorImage.SetSuggestedHeightInInches( ::PixelsToInches( rRealOutputSize.m_dy, (uLONG) screenDPI.m_dy ) ); // Create an offscreen drawing surface and set the picture ROffscreenDrawingSurface rODS; rODS.SetImage( &vectorImage ); // Scale to the device DPI RRealSize rRealImageSize = pImage->GetSizeInLogicalUnits(); R2dTransform transform ; RRealSize deviceDPI = rODS.GetDPI(); transform.PreScale( (YFloatType) deviceDPI.m_dx / screenDPI.m_dy, (YFloatType) deviceDPI.m_dy / screenDPI.m_dy ); transform.PreScale( rRealOutputSize.m_dx / rRealImageSize.m_dx, rRealOutputSize.m_dy / rRealImageSize.m_dy ) ; // calculate the output rect RRealRect outputRect( rRealOutputSize ) ; ::ScreenUnitsToLogicalUnits( outputRect ); outputRect *= transform; // render to the offscreen pImage->Render( rODS, outputRect ) ; // clean up rODS.ReleaseImage(); // export rLibrary.ExportImage( vectorImage, strPathName, kImageFormatXRX ) ; if (rLibrary.GetLastException() != kNoError) { throw rLibrary.GetLastException() ; } } else // all other formats { _nFilterIndex = dlg.m_ofn.nFilterIndex ; EImageFormat eFormat = (EImageFormat) arrFileFormats[dlg.m_ofn.nFilterIndex - 1] ; rLibrary.ExportImage( *pImage, strPathName, eFormat ); if (rLibrary.GetLastException() != kNoError) { throw rLibrary.GetLastException() ; } } } catch( YException e) { ReportException( e ) ; } } }
////////////////////////////////////////////////////////////////////////////// // // void ExportGraphicComponent( RComponentView* pComponentView, RMBCString *pInitialDir ) // // export a graphic to file from a component view // ////////////////////////////////////////////////////////////////////////////// void ExportGraphicComponent( RComponentView* pComponentView, RMBCString *pInitialDir /*=NULL*/) { RImageLibrary rLibrary ; CArray<int, int> arrFileFormats ; // // Build the export file filter list... // CString strFilter, str ; for (int i = 0; i < kNumFormats - 1; i++) { if (rLibrary.IsFormatSupported( (EImageFormat) kImageExportFilters[i][0] )) { str.LoadString( kImageExportFilters[i][1] ) ; strFilter += str ; arrFileFormats.Add( kImageExportFilters[i][0] ) ; } } TpsAssert( kImageExportFilters[i][0] == kImageFormatXRX, "Invalid export format!" ) ; str.LoadString( kImageExportFilters[i][1] ) ; strFilter += str ; strFilter += "|" ; arrFileFormats.Add( kImageExportFilters[i][0] ) ; // // Create and execute the dialog... // RExportGraphicDlg dlg( pComponentView, strFilter ) ; // Load in the dialog title string CString strTitle ; strTitle.LoadString( STRING_EXPORT_IMAGE_DIALOG_TITLE ) ; dlg.m_ofn.lpstrTitle = (LPCTSTR) strTitle ; if( pInitialDir ) { dlg.m_ofn.lpstrInitialDir = (LPCTSTR)*pInitialDir; } if (IDOK == dlg.DoModal()) { RMBCString strPathName = dlg.GetPathName() ; RIntSize szImageSize = dlg.GetSize() ; _nFilterIndex = dlg.m_ofn.nFilterIndex ; EImageFormat eFormat = (EImageFormat) arrFileFormats[dlg.m_ofn.nFilterIndex - 1] ; RRealSize pictureSize = pComponentView->GetReferenceSize() ; try { if (kImageFormatXRX == eFormat) { RRealSize outputSize( szImageSize.m_dx, szImageSize.m_dy ) ; // = pictureSize ; RRealSize screenDPI = ::GetScreenDPI() ; RVectorImage vectorImage ; vectorImage.SetSuggestedWidthInInches( ::PixelsToInches( outputSize.m_dx, (uLONG) screenDPI.m_dx ) ) ; vectorImage.SetSuggestedHeightInInches( ::PixelsToInches( outputSize.m_dy, (uLONG) screenDPI.m_dy ) ) ; // Create an offscreen drawing surface and set the picture ROffscreenDrawingSurface drawingSurface; drawingSurface.SetImage( &vectorImage ); R2dTransform transform ; // Scale to the device DPI RRealSize deviceDPI = drawingSurface.GetDPI( ); transform.PreScale( (YFloatType) deviceDPI.m_dx / screenDPI.m_dy, (YFloatType) deviceDPI.m_dy / screenDPI.m_dy ); transform.PreScale( outputSize.m_dx / pictureSize.m_dx, outputSize.m_dy / pictureSize.m_dy ) ; // Render the component RRealRect outputRect( pictureSize ) ; pComponentView->Render( drawingSurface, transform, outputRect ) ; drawingSurface.ReleaseImage( ); rLibrary.ExportImage( vectorImage, strPathName, kImageFormatXRX ) ; if (rLibrary.GetLastException() != kNoError) { throw rLibrary.GetLastException() ; } } // if (XRX) else { // Check for a image interface RImageInterface* pInterface = (RImageInterface *) pComponentView->GetInterface( kImageInterfaceId ) ; if (pInterface) { pInterface->Export( strPathName, eFormat ) ; delete pInterface ; } else { // Initialize the new bitmap at a bit depth of 24 RBitmapImage image ; image.Initialize( szImageSize.m_dx, szImageSize.m_dy, 24 ) ; ROffscreenDrawingSurface dsMem ; dsMem.SetImage( &image ) ; R2dTransform transform ; transform.PreScale( szImageSize.m_dx / pictureSize.m_dx, szImageSize.m_dy / pictureSize.m_dy ) ; // Render the component dsMem.SetFillColor( RSolidColor( kWhite ) ) ; dsMem.FillRectangle( RRealRect( pictureSize ), transform ) ; pComponentView->Render( dsMem, transform, RIntRect( RIntSize( pictureSize.m_dx, pictureSize.m_dy ) ) ) ; dsMem.ReleaseImage() ; rLibrary.ExportImage( image, strPathName, eFormat ) ; } if (rLibrary.GetLastException() != kNoError) { throw rLibrary.GetLastException() ; } } // else } // try catch( YException e) { ReportException( e ) ; } } // if (IDOK) }
bool repl_command(std::string &line, v8::Local<v8::Array> cmds) { _parser p(line); std::string cmd_word; result_t hr; int32_t len = cmds->Length(); int32_t i; p.skipSpace(); p.getWord(cmd_word); if (!qstrcmp(cmd_word.c_str(), ".help")) { std::string help_str = ".exit Exit the repl\n" ".help Show repl options\n" ".info Show fibjs build information"; Isolate* isolate = Isolate::current(); for (i = 0; i < len; i ++) { v8::Local<v8::Value> v = cmds->Get(i); v8::Local<v8::Object> o; std::string cmd; std::string help; hr = GetArgumentValue(v, o, true); if (hr >= 0) { hr = GetConfigValue(isolate->m_isolate, o, "cmd", cmd, true); if (hr >= 0) hr = GetConfigValue(isolate->m_isolate, o, "help", help, true); } if (hr < 0) { output(console_base::_ERROR, "Invalid cmds argument."); return false; } cmd.append(10, ' '); help_str = help_str + "\n" + cmd.substr(0, 10) + help; } output(console_base::_INFO, help_str); return true; } if (!qstrcmp(cmd_word.c_str(), ".exit")) return false; if (!qstrcmp(cmd_word.c_str(), ".info")) { v8::Local<v8::Object> o; util_base::buildInfo(o); console_base::dir(o); return true; } Isolate* isolate = Isolate::current(); for (i = 0; i < len; i ++) { v8::Local<v8::Value> v = cmds->Get(i); v8::Local<v8::Object> o; std::string cmd; v8::Local<v8::Function> exec; hr = GetArgumentValue(v, o, true); if (hr >= 0) { hr = GetConfigValue(isolate->m_isolate, o, "cmd", cmd, true); if (hr >= 0) hr = GetConfigValue(isolate->m_isolate, o, "exec", exec, true); } if (hr < 0) { output(console_base::_ERROR, "Invalid cmds argument."); return false; } if (!qstrcmp(cmd_word.c_str(), cmd.c_str())) { v8::Local<v8::Array> argv = v8::Array::New(isolate->m_isolate); int32_t n = 0; while (!cmd_word.empty()) { argv->Set(n ++, GetReturnValue(isolate->m_isolate, cmd_word)); p.skipSpace(); p.getWord(cmd_word); } TryCatch try_catch; v = argv; v = exec->Call(o, 1, &v); if (v.IsEmpty()) ReportException(try_catch, 0); return true; } } output(console_base::_ERROR, cmd_word + ": command not found."); return true; }
result_t SandBox::Context::repl(v8::Local<v8::Array> cmds, Stream_base* out) { result_t hr = 0; std::string buf; v8::Local<v8::Value> v, v1; Isolate* isolate = Isolate::current(); v8::Local<v8::String> strFname = isolate->NewFromUtf8("repl", 4); obj_ptr<BufferedStream_base> bs; stream_logger* logger = NULL; if (out) { if ((logger = s_stream) != NULL) { s_stream = NULL; logger->close(); } s_stream = logger = new stream_logger(out); bs = new BufferedStream(out); } output(console_base::_INFO, "Type \".help\" for more information."); while (true) { if (!v.IsEmpty() && !v->IsUndefined()) console_base::dir(v); v = v1; std::string line; if (out) { output(console_base::_PRINT, buf.empty() ? "> " : " ... "); hr = bs->ac_readLine(-1, line); if (hr >= 0) s_std->log(console_base::_INFO, line); } else hr = console_base::ac_readLine(buf.empty() ? "> " : " ... ", line); if (hr < 0) break; if (line.empty()) continue; if (line[0] == '.') { if (!repl_command(line, cmds)) break; continue; } buf += line; buf.append("\n", 1); { v8::Local<v8::Script> script; TryCatch try_catch; script = v8::Script::Compile(isolate->NewFromUtf8(buf), strFname); if (script.IsEmpty()) { v8::String::Utf8Value exception(try_catch.Exception()); if (*exception && qstrcmp(*exception, "SyntaxError: Unexpected end of input")) { buf.clear(); ReportException(try_catch, 0); } continue; } buf.clear(); v = script->Run(); if (v.IsEmpty()) ReportException(try_catch, 0); } } if (out) { if (logger == s_stream) s_stream = NULL; delete logger; } return hr; }
static void ReportException(Environment* env, const v8::TryCatch& try_catch) { ReportException(env, try_catch.Exception(), try_catch.Message()); }