v8::Handle<v8::String> V8::toJson(v8::Handle<v8::Value> value) { HandleScope scope; Handle<Context> context = Context::GetCurrent(); Handle<Object> global = context->Global(); Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject(); Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify"))); TryCatch exception; Handle<Value> argv[] = { value, v8::Null(), v8::String::New("\t") }; if (exception.HasCaught()) { throw chi::Exception(chi::V8::ReportException(exception)); } Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv); if (exception.HasCaught()) { throw chi::Exception(chi::V8::ReportException(exception)); } return scope.Close(stringified.As<String>()); }
void test_Exception() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Handle<Script> script = Script::New(String::New("function foo(x) { throw x; };")); Context::Scope scope(context); TryCatch trycatch; Handle<Value> v = script->Run(); do_check_true(!v.IsEmpty()); do_check_true(!trycatch.HasCaught()); Handle<Function> fn = context->Global()->Get(String::NewSymbol("foo")).As<Function>(); do_check_true(!fn.IsEmpty()); Local<Value> args[1] = { Integer::New(4) }; v = fn->Call(context->Global(), 1, args); do_check_true(v.IsEmpty()); do_check_true(trycatch.HasCaught()); Handle<Value> exn = trycatch.Exception(); do_check_true(exn->IsInt32()); do_check_eq(exn->Int32Value(), 4); context.Dispose(); }
/* static */ void V8Runtime::bootstrap(Local<Object> global) { EventEmitter::Initialize(); krollGlobalObject = Persistent<Object>::New(Object::New()); DEFINE_METHOD(krollGlobalObject, "log", krollLog); DEFINE_METHOD(krollGlobalObject, "binding", KrollBindings::getBinding); DEFINE_TEMPLATE(krollGlobalObject, "EventEmitter", EventEmitter::constructorTemplate); krollGlobalObject->Set(String::NewSymbol("runtime"), String::New("v8")); LOG_TIMER(TAG, "Executing kroll.js"); TryCatch tryCatch; Handle<Value> result = V8Util::executeString(KrollBindings::getMainSource(), String::New("kroll.js")); if (tryCatch.HasCaught()) { V8Util::reportException(tryCatch, true); } if (!result->IsFunction()) { LOGF(TAG, "kroll.js result is not a function"); V8Util::reportException(tryCatch, true); } Handle<Function> mainFunction = Handle<Function>::Cast(result); Local<Value> args[] = { Local<Value>::New(krollGlobalObject) }; mainFunction->Call(global, 1, args); if (tryCatch.HasCaught()) { V8Util::reportException(tryCatch, true); LOGE(TAG, "Caught exception while bootstrapping Kroll"); } }
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
jobject NativePlatform::RunScript(JNIEnv *_env, jobject obj, jstring scriptFile) { JEnv env(_env); jobject res = nullptr; auto isolate = g_isolate; Isolate::Scope isolate_scope(isolate); HandleScope handleScope(isolate); auto context = isolate->GetCurrentContext(); auto filename = ArgConverter::jstringToString(scriptFile); auto src = File::ReadText(filename); auto source = ConvertToV8String(src); TryCatch tc; Local<Script> script; ScriptOrigin origin(ConvertToV8String(filename)); auto maybeScript = Script::Compile(context, source, &origin).ToLocal(&script); if(tc.HasCaught()) { throw NativeScriptException(tc, "Script " + filename + " contains compilation errors!"); } if (!script.IsEmpty()) { Local<Value> result; auto maybeResult = script->Run(context).ToLocal(&result); if(tc.HasCaught()) { throw NativeScriptException(tc, "Error running script " + filename); } if (!result.IsEmpty()) { res = ConvertJsValueToJavaObject(env, result, static_cast<int>(Type::Null)); } else { DEBUG_WRITE(">>runScript maybeResult is empty"); } } else { DEBUG_WRITE(">>runScript maybeScript is empty"); } return res; }
v8::Handle<v8::Value> toJson(v8::Handle<v8::Value> value) { HandleScope scope; Handle<Context> context = Context::GetCurrent(); Handle<Object> global = context->Global(); Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject(); Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify"))); // JSON.stringify(values, null, '\t'); Handle<Value> argv[] = { value, Null(), String::New("\t") }; TryCatch exception; Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv); if (exception.HasCaught()) { return exception.ReThrow(); } return scope.Close(stringified); }
void JSAttributeTest::requestValueWithCallbackTestOnlyFirstTime(std::shared_ptr<JSZAttribute> &jsZAttribute, std::shared_ptr<ZCLAttribute> attributeMock, Callbacks &changeSignal) { ZDevice zDevice{createZDevice()}; std::stringstream stream; stream << "var f = function (){\n"; stream << " var log = Log();\n"; stream << " log.info('callback called')"; stream << "};\n"; stream << zAttributeVariable << "\n"; stream << "var b = a.requestValue(f);\n"; V8_SETUP jsZAttribute->initJsObjectsTemplate(isolate, global); jsLog->initJsObjectsTemplate(isolate, global); setInitExpectation(zDevice, attributeMock); TryCatch tryCatch; v8::Local<v8::Value> result = runScript(stream.str()); if (tryCatch.HasCaught()) { String::Utf8Value value(tryCatch.Message()->Get()); } ASSERT_THAT(result.IsEmpty(), false); ASSERT_THAT(result->IsUndefined(), true); changeSignal(); result = runScript(""); result = runScript(""); ASSERT_THAT(log.empty(), false); Log::LogData logData = log.get(); ASSERT_THAT(logData.msg, StrEq("callback called")); ASSERT_THAT(log.empty(), true); }
Local<Object> Module::LoadData(Isolate *isolate, const string& path) { Local<Object> json; auto jsonData = File::ReadText(path); TryCatch tc; auto jsonStr = ConvertToV8String(jsonData); auto maybeValue = JSON::Parse(isolate, jsonStr); if (maybeValue.IsEmpty() || tc.HasCaught()) { string errMsg = "Cannot parse JSON file " + path; throw NativeScriptException(tc, errMsg); } auto value = maybeValue.ToLocalChecked(); if (!value->IsObject()) { string errMsg = "JSON is not valid, file=" + path; throw NativeScriptException(errMsg); } json = value.As<Object>(); return json; }
bool v8test_eval() { BEGINTEST(); HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Local<Object> qmlglobal = Object::New(); qmlglobal->Set(String::New("a"), Integer::New(1922)); Local<Script> script = Script::Compile(String::New("eval(\"a\")"), NULL, NULL, Handle<String>(), Script::QmlMode); TryCatch tc; Local<Value> result = script->Run(qmlglobal); VERIFY(!tc.HasCaught()); VERIFY(result->Int32Value() == 1922); cleanup: context.Dispose(); ENDTEST(); }
void Event(Pollpri * p, int revents) { HandleScope scope; PRINTF("fd = %d, epfd = %d, revents = 0x%0x\n", fd, epfd, revents); if(revents != EV_READ) { printf("fd = %d, epfd = %d, revents = 0x%0x\n", fd, epfd, revents); return; } int m = 0; char buf[64]; m = lseek(fd, 0, SEEK_SET); PRINTF("seek(%d) %d bytes: %s\n", fd, m, strerror(errno)); m = read(fd, &buf, 63); buf[m] = 0; PRINTF("read(%d) %d bytes (%s): %s\n", fd, m, buf, strerror(errno)); Local<Value> emit_v = handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local<Function> emit_f = emit_v.As<Function>(); Handle<Value> argv[2]; argv[0] = String::New("edge"); argv[1] = String::New(buf); TryCatch tc; emit_f->Call(handle_, 2, argv); if(tc.HasCaught()) { FatalException(tc); } }
stdext::ustring JavaScriptContext::ExecuteReturnString(const stdext::ustring & source, const stdext::ustring & name, stdext::ustring & error) { stdext::ustring resultString; error = wstringToUstring(L""); Locker locker(m_isolate); Isolate::Scope isolate_scope(m_isolate); { Context::Scope contextScope(*m_ctx); HandleScope scope; Local<String> scriptSource = String::New(reinterpret_cast<const uint16_t *>(source.c_str())); Local<String> scriptName = String::New(reinterpret_cast<const uint16_t *>(name.c_str())); Local<Script> script = Script::New(scriptSource, scriptName); Local<Value> result; { TryCatch tryCatch; result = script->Run(); if (!result.IsEmpty()) { String::Value value(result); resultString.append(reinterpret_cast<const char16_t *>(*value)); } if (tryCatch.HasCaught()) { error.append(wstringToUstring(L"Error running script: ")); error.append(name); error.append(wstringToUstring(L" - ")); String::Value stackTrace(tryCatch.StackTrace()); error.append(reinterpret_cast<const char16_t*>(*stackTrace)); } } } return resultString; }
JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeEvalString (JNIEnv *env, jobject self, jstring source, jstring filename) { ENTER_V8(V8Runtime::globalContext); titanium::JNIScope jniScope(env); Handle<Value> jsSource = TypeConverter::javaStringToJsString(env, source); if (jsSource.IsEmpty() || !jsSource->IsString()) { LOGE(TAG, "Error converting Javascript string, aborting evalString"); return NULL; } Handle<Value> jsFilename = TypeConverter::javaStringToJsString(env, filename); TryCatch tryCatch; Handle<Script> script = Script::Compile(jsSource->ToString(), jsFilename); Local<Value> result = script->Run(); if (tryCatch.HasCaught()) { V8Util::openJSErrorDialog(tryCatch); V8Util::reportException(tryCatch, true); return NULL; } return TypeConverter::jsValueToJavaObject(env, result); }
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeSetWindow (JNIEnv *env, jobject javaKrollWindow, jlong ptr, jobject javaWindow) { ENTER_V8(V8Runtime::globalContext); titanium::JNIScope jniScope(env); Handle<Object> jsKrollWindow; if (ptr != 0) { jsKrollWindow = Persistent<Object>((Object *) ptr); } else { jsKrollWindow = TypeConverter::javaObjectToJsValue(env, javaKrollWindow)->ToObject(); } Handle<Value> setWindowValue = jsKrollWindow->Get(String::New("setWindow")); if (!setWindowValue->IsFunction()) { return; } Handle<Function> setWindow = Handle<Function>::Cast(setWindowValue->ToObject()); Handle<Value> jsWindow = TypeConverter::javaObjectToJsValue(env, javaWindow); TryCatch tryCatch; if (!jsWindow->IsNull()) { Handle<Value> args[] = { jsWindow }; setWindow->Call(jsKrollWindow, 1, args); } if (tryCatch.HasCaught()) { V8Util::openJSErrorDialog(tryCatch); V8Util::reportException(tryCatch); } }
static int EIO_AfterIndex(eio_req* req) { HandleScope scope; index_baton_t* baton = static_cast<index_baton_t*>(req->data); ev_unref(EV_DEFAULT_UC); baton->lucene->Unref(); Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = v8::String::New(baton->error.c_str()); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = v8::Integer::NewFromUnsigned((uint32_t)baton->indexTime); } TryCatch tryCatch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (tryCatch.HasCaught()) { FatalException(tryCatch); } baton->callback.Dispose(); delete baton->index; delete baton; return 0; }
/* * Class: org_appcelerator_kroll_runtime_v8_V8Runtime * Method: nativeRunModule * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeRunModule (JNIEnv *env, jobject self, jstring source, jstring filename, jobject activityProxy) { ENTER_V8(V8Runtime::globalContext); titanium::JNIScope jniScope(env); if (moduleObject.IsEmpty()) { moduleObject = Persistent<Object>::New( V8Runtime::krollGlobalObject->Get(String::New("Module"))->ToObject()); runModuleFunction = Persistent<Function>::New( Handle<Function>::Cast(moduleObject->Get(String::New("runModule")))); } Handle<Value> jsSource = TypeConverter::javaStringToJsString(source); Handle<Value> jsFilename = TypeConverter::javaStringToJsString(filename); Handle<Value> jsActivity = TypeConverter::javaObjectToJsValue(activityProxy); Handle<Value> args[] = { jsSource, jsFilename, jsActivity }; TryCatch tryCatch; runModuleFunction->Call(moduleObject, 3, args); if (tryCatch.HasCaught()) { V8Util::openJSErrorDialog(tryCatch); V8Util::reportException(tryCatch, true); } }
int Interface::UserInvoke(JNIEnv *jniEnv, Handle<Object> target, int opIdx, jobjectArray jArgs, jobject *jResult) { HandleScope scope; TryCatch tryCatch; Operation *op = operations->addr(opIdx); int result = OK; for(int i = 0; result == OK && i < op->argCount; i++) { result = conv->ToV8Value(jniEnv, jniEnv->GetObjectArrayElement(jArgs, i), op->argTypes[i], &op->vArgs[i]); } if(result == OK) { Handle<Value> vRes; if(target->IsFunction() && parent == 0 && operations->getLength() == 1) { /* invoke as function if target is a function, and interface delcares only one operation */ vRes = (Handle<Function>::Cast(target))->Call(target, op->argCount, op->vArgs); } else { /* locate the method and invoke that */ Handle<Value> vMethod = target->Get(op->name); if(!vMethod.IsEmpty() && vMethod->IsFunction()) { vRes = Handle<Function>::Cast(vMethod)->Call(target, op->argCount, op->vArgs); } } if(!vRes.IsEmpty() && op->type != TYPE_UNDEFINED) { jobject ob; result = conv->ToJavaObject(jniEnv, vRes, op->type, &ob); if(result == OK) { *jResult = ob; } } } if(tryCatch.HasCaught()) { result = ErrorJS; tryCatch.Reset(); } return result; }
void test_obj_propexn() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Handle<Object> obj = Object::New(); obj->SetAccessor(String::New("myprop"), ReadExn, WriteExn); Local<Object> global = context->Global(); global->Set(String::New("testobj"), obj); Handle<String> source = String::New("var n = 0;" "try { testobj.myprop; } catch (e) { n += e; };" "try { testobj.myprop = (n+9); } catch (e) { n += e; }; n"); // Compile the source code. Handle<Script> script = Script::Compile(source); TryCatch trycatch; // Run the script to get the result. Handle<Value> result = script->Run(); do_check_false(result.IsEmpty()); do_check_true(result->IsInt32()); do_check_false(trycatch.HasCaught()); JSInt32 i = result->Int32Value(); do_check_eq(13, i); context.Dispose(); }
Script *v8ScriptService::scriptFromCode(const std::string &code, const boost::filesystem::path &filename) { HandleScope scope; // Instantiate the v8 script. TryCatch exception; Handle<v8::Script> script = v8::Script::New( String::New(code.c_str()), String::New(filename.string().c_str()) ); if (exception.HasCaught()) { throw script_compilation_error( V8::stringifyException(exception), code ); } // Cast and ensure the factory is correct. AbstractFactory<v8Script> *v8ScriptFactory; v8ScriptFactory = dynamic_cast<AbstractFactory<v8Script> *>( Script::factoryManager.instance() ); if (NULL == v8ScriptFactory) { throw script_compilation_error("Concrete v8 factory mismatch!"); } // Instantiate our script and return it. return v8ScriptFactory->create(script); }
void CoreClrFuncInvokeContext::InvokeCallback(void* data) { DBG("CoreClrFuncInvokeContext::InvokeCallback"); CoreClrFuncInvokeContext* context = (CoreClrFuncInvokeContext*)data; v8::Handle<v8::Value> callbackData = NanNull(); v8::Handle<v8::Value> errors = NanNull(); if (context->taskState == TaskStatus::Faulted) { errors = CoreClrFunc::MarshalCLRToV8(context->resultData, context->resultType); } else { callbackData = CoreClrFunc::MarshalCLRToV8(context->resultData, context->resultType); } Handle<Value> argv[] = { errors, callbackData }; int argc = 2; TryCatch tryCatch; NanNew<v8::Function>(*(context->callback))->Call(NanGetCurrentContext()->Global(), argc, argv); delete context; if (tryCatch.HasCaught()) { node::FatalException(tryCatch); } }
static int EIO_AfterSearch(eio_req* req) { HandleScope scope; search_baton_t* baton = static_cast<search_baton_t*>(req->data); ev_unref(EV_DEFAULT_UC); baton->lucene->Unref(); Handle<Value> argv[2]; if (baton->error.empty()) { argv[0] = Null(); // Error arg, defaulting to no error argv[1] = baton->results; } else { argv[0] = String::New(baton->error.c_str()); argv[1] = Null(); } TryCatch tryCatch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (tryCatch.HasCaught()) { FatalException(tryCatch); } baton->callback.Dispose(); if (!baton->results.IsEmpty()) baton->results.Dispose(); delete baton->index; delete baton->search; delete baton; return 0; }
int ArrayConv::UserGetElement(JNIEnv *jniEnv, Handle<Object> val, unsigned int elementType, int idx, jobject *jVal) { HandleScope scope; TryCatch tryCatch; Handle<Value> vElement = val->Get(idx); if(vElement.IsEmpty()) return ErrorNotfound; if(tryCatch.HasCaught()) return ErrorJS; return conv->ToJavaObject(jniEnv, vElement, elementType, jVal); }
void Queue::Start(bool qMsg){ //BOOL b = EnumThreadWindows(_thid,&EnumThreadWndProc,0); if(!qMsg){ _thid = ::GetCurrentThreadId(); _wait.Signal(); _wait.Close(); MSG msg; while(::GetMessage(&msg,0,0,0)){ HandleScope store; TryCatch err; if(msg.message==WM_QUEUE){ QECALL proc = (QECALL)(UINT_PTR)msg.wParam; void* param = (void*)msg.lParam; proc(param); }else{ TranslateMessage(&msg); DispatchMessage(&msg); } if(err.HasCaught()) ReportError(err); } return; } if(_handle==0||_handle==INVALID_HANDLE_VALUE){ _handle = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE,0,0,1); _wait.Signal(); _wait.Close(); } DWORD id; ULONG_PTR data; LPOVERLAPPED ol; while(GetQueuedCompletionStatus(_handle,&id,(PULONG_PTR)&data,&ol,INFINITE)){ if(data==0) break; HandleScope store; TryCatch err; QECALL proc = (QECALL)(UINT_PTR)id; void* param = (void*)data; proc(param); if(err.HasCaught()) ReportError(err); } ::CloseHandle(_handle); _handle = 0; }
Local<Script> Module::LoadScript(Isolate *isolate, const string& path, const Local<String>& fullRequiredModulePath) { Local<Script> script; TryCatch tc; auto scriptText = Module::WrapModuleContent(path); DEBUG_WRITE("Compiling script (module %s)", path.c_str()); // auto cacheData = TryLoadScriptCache(path); ScriptOrigin origin(fullRequiredModulePath); ScriptCompiler::Source source(scriptText, origin, cacheData); ScriptCompiler::CompileOptions option = ScriptCompiler::kNoCompileOptions; if (cacheData != nullptr) { option = ScriptCompiler::kConsumeCodeCache; auto maybeScript = ScriptCompiler::Compile(isolate->GetCurrentContext(), &source, option); if (maybeScript.IsEmpty() || tc.HasCaught()) { throw NativeScriptException(tc, "Cannot compile " + path); } script = maybeScript.ToLocalChecked(); } else { if (Constants::V8_CACHE_COMPILED_CODE) { option = ScriptCompiler::kProduceCodeCache; } auto maybeScript = ScriptCompiler::Compile(isolate->GetCurrentContext(), &source, option); if (maybeScript.IsEmpty() || tc.HasCaught()) { throw NativeScriptException(tc, "Cannot compile " + path); } script = maybeScript.ToLocalChecked(); SaveScriptCache(source, path); } DEBUG_WRITE("Compiled script (module %s)", path.c_str()); return script; }
int ArrayConv::UserGetLength(JNIEnv *jniEnv, Handle<Object> val, int *length) { HandleScope scope; TryCatch tryCatch; Handle<Value> vLength = val->Get(sLength); if(vLength.IsEmpty()) return ErrorNotfound; if(tryCatch.HasCaught()) return ErrorJS; *length = (int)vLength->IntegerValue(); return OK; }
Handle<Value> CallFunc(Handle<Object>& self,Handle<Function>& func,int argc,Handle<Value>* argv){ TryCatch err; Handle<Value> ret = func->Call(self,argc,argv); if(err.HasCaught()){ ReportError(err); return Undefined(); } return ret; }
std::string GetException(TryCatch &try_catch, result_t hr) { if (try_catch.HasCaught()) { v8::String::Utf8Value exception(try_catch.Exception()); v8::Local<v8::Message> message = try_catch.Message(); if (message.IsEmpty()) return ToCString(exception); else { v8::Local<v8::Value> trace_value = try_catch.StackTrace(); if (!IsEmpty(trace_value)) { v8::String::Utf8Value stack_trace(trace_value); return ToCString(stack_trace); } std::string strError; v8::String::Utf8Value filename(message->GetScriptResourceName()); if (qstrcmp(ToCString(exception), "SyntaxError: ", 13)) { strError.append(ToCString(exception)); strError.append("\n at "); } else { strError.append((ToCString(exception) + 13)); strError.append("\n at "); } strError.append(ToCString(filename)); int lineNumber = message->GetLineNumber(); if (lineNumber > 0) { char numStr[32]; strError.append(1, ':'); sprintf(numStr, "%d", lineNumber); strError.append(numStr); strError.append(1, ':'); sprintf(numStr, "%d", message->GetStartColumn() + 1); strError.append(numStr); } return strError; } } else if (hr < 0) return getResultMessage(hr); return ""; }
void JsContext::onDraw(SkCanvas* canvas) { // Record canvas and window in this. fCanvas = canvas; // Create a handle scope to keep the temporary object references. HandleScope handleScope(fGlobal->getIsolate()); // Create a local context from our global context. Local<Context> context = fGlobal->getContext(); // Enter the context so all the remaining operations take place there. Context::Scope contextScope(context); // Wrap the C++ this pointer in a JavaScript wrapper. Handle<Object> contextObj = this->wrap(); // Set up an exception handler before calling the Process function. TryCatch tryCatch; // Invoke the process function, giving the global object as 'this' // and one argument, this JsContext. const int argc = 1; Handle<Value> argv[argc] = { contextObj }; Local<Function> onDraw = Local<Function>::New(fGlobal->getIsolate(), fOnDraw); Handle<Value> result = onDraw->Call(context->Global(), argc, argv); // Handle any exceptions or output. if (result.IsEmpty()) { SkASSERT(tryCatch.HasCaught()); // Print errors that happened during execution. fGlobal->reportException(&tryCatch); } else { SkASSERT(!tryCatch.HasCaught()); if (!result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. String::Utf8Value str(result); const char* cstr = to_cstring(str); printf("%s\n", cstr); } } }
// Callback function for SkEvents used to implement timeouts. bool Global::TimeOutProc(const SkEvent& evt) { // Create a handle scope to keep the temporary object references. HandleScope handleScope(gGlobal->getIsolate()); // Create a local context from our global context. Local<Context> context = gGlobal->getContext(); // Enter the context so all the remaining operations take place there. Context::Scope contextScope(context); // Set up an exception handler before calling the Process function. TryCatch tryCatch; int32_t id = evt.getFast32(); if (gGlobal->fTimeouts.find(gGlobal->fLastTimerID) == gGlobal->fTimeouts.end()) { printf("Not a valid timer ID.\n"); return true; } const int argc = 0; Local<Function> onTimeout = Local<Function>::New(gGlobal->getIsolate(), gGlobal->fTimeouts[id]); Handle<Value> result = onTimeout->Call(context->Global(), argc, NULL); gGlobal->fTimeouts.erase(id); // Handle any exceptions or output. if (result.IsEmpty()) { SkASSERT(tryCatch.HasCaught()); // Print errors that happened during execution. gGlobal->reportException(&tryCatch); } else { SkASSERT(!tryCatch.HasCaught()); if (!result->IsUndefined()) { // If all went well and the result wasn't undefined then print the // returned value. String::Utf8Value str(result); const char* cstr = to_cstring(str); printf("%s\n", cstr); } } return true; }
int ArrayConv::UserSetElement(JNIEnv *jniEnv, Handle<Object> val, unsigned int elementType, int idx, jobject jVal) { HandleScope scope; TryCatch tryCatch; Handle<Value> vElement; int result = conv->ToV8Value(jniEnv, jVal, elementType, &vElement); if(result == OK) { val->Set(idx, vElement); if(tryCatch.HasCaught()) result = ErrorJS; } return result; }
std::string v8ScriptService::preCompileCode(const std::string &code, const boost::filesystem::path &filename) { HandleScope scope; std::string filenameString = filename.string(); bool isCoffee = false; bool isLiterateCoffee = false; if (boost::regex_search( filenameString, regex(".*\\.coffee$") )) { isCoffee = true; } if (boost::regex_search( filenameString, regex(".*\\.litcoffee$") )) { isCoffee = true; isLiterateCoffee = true; } // Compile coffeescript to JS. if (isCoffee) { TryCatch exception; Handle<Object> CoffeeScript = Context::GetCurrent()->Global()->Get(String::New("CoffeeScript")).As<Object>(); Handle<Function> compile = CoffeeScript->Get(String::New("compile")).As<Function>(); Handle<Object> options = Object::New(); options->Set(String::New("filename"), String::New( filenameString.c_str() )); options->Set(String::New("literate"), Boolean::New(isLiterateCoffee)); Handle<Value> args[] = { String::New(code.c_str()), options }; Handle<Value> result = compile->Call(compile, 2, args); if (exception.HasCaught()) { throw script_precompilation_error(V8::stringifyException(exception, true)); } return V8::stringToStdString(result->ToString()); } else { return code; } }