Ejemplo n.º 1
0
JavaClass_hasInstance(JSContext *cx, JSObject *obj, jsval candidate_jsval,
                      JSBool *has_instancep)
{
    JavaClassDescriptor *class_descriptor;
    JavaObjectWrapper *java_wrapper;
    JSClass *js_class;
    JSBool has_instance;
    JSObject *candidate_obj;
    jclass java_class;
    jobject java_obj;
    JNIEnv *jEnv;
    JSJavaThreadState *jsj_env;
    
    has_instance = JS_FALSE;
    class_descriptor = JS_GetPrivate(cx, obj);
    if (!class_descriptor) {
        JS_ReportErrorNumber(cx, jsj_GetErrorMessage, NULL, 
                                                    JSJMSG_BAD_OP_JCLASS);
        return JS_FALSE;
    }

    /*
     * Make sure that the thing to the left of the instanceof operator is a
     * Java object.
     */
    if (!JSVAL_IS_OBJECT(candidate_jsval))
        goto done;
    candidate_obj = JSVAL_TO_OBJECT(candidate_jsval);
#ifdef JS_THREADSAFE
    js_class = JS_GetClass(cx, candidate_obj);
#else
    js_class = JS_GetClass(candidate_obj);
#endif
    if ((js_class != &JavaObject_class) && (js_class != &JavaArray_class))
        goto done;

    java_class = class_descriptor->java_class;
    java_wrapper = JS_GetPrivate(cx, candidate_obj);
    if (!java_wrapper) {
        JS_ReportErrorNumber(cx, jsj_GetErrorMessage, NULL, 
                                                JSJMSG_BAD_OP_PROTO);
        return JS_FALSE;
    }
    java_obj = java_wrapper->java_obj;
    /* Get JNI pointer */
    jsj_env = jsj_EnterJava(cx, &jEnv);
    has_instance = (*jEnv)->IsInstanceOf(jEnv, java_obj, java_class);
    jsj_ExitJava(jsj_env);

done:
    *has_instancep = has_instance;
    return JS_TRUE;
}
Ejemplo n.º 2
0
/* Mimick the behaviour exposed by standard Error objects
   (http://mxr.mozilla.org/mozilla-central/source/js/src/jsexn.cpp#554)
*/
static char*
jsvalue_to_string(JSContext* cx, jsval val, gboolean* is_string)
{
    char* value = NULL;
    JSString* value_str = NULL;

    if (JSVAL_IS_PRIMITIVE(val)) {
      value_str = JS_ValueToSource(cx, val);
    } else {
      JSObject *obj = JSVAL_TO_OBJECT(val);

      if (JS_ObjectIsFunction(cx, obj)) {
	JSFunction *fn = JS_ValueToFunction(cx, val);
	value_str = JS_GetFunctionId(fn);

	if (!value_str)
	  value = g_strdup("[unknown function]");
      } else {
	value = g_strdup_printf("[object %s]", JS_GetClass(cx, obj)->name);
      }
    }

    if (!value && value_str)
      value = gjs_value_debug_string(cx, val);

    if (is_string)
        *is_string = JSVAL_IS_STRING(val);

    return value;
}
Ejemplo n.º 3
0
JSObject*
gjs_param_from_g_param(JSContext    *context,
                       GParamSpec   *gparam)
{
    JSObject *obj;
    Param *priv;

    if (gparam == NULL)
        return NULL;

    gjs_debug(GJS_DEBUG_GPARAM,
              "Wrapping %s '%s' on %s with JSObject",
              g_type_name(G_TYPE_FROM_INSTANCE((GTypeInstance*) gparam)),
              gparam->name,
              g_type_name(gparam->owner_type));

    JS::RootedObject proto(context, gjs_lookup_param_prototype(context));

    obj = JS_NewObjectWithGivenProto(context, JS_GetClass(proto), proto);

    GJS_INC_COUNTER(param);
    priv = g_slice_new0(Param);
    JS_SetPrivate(obj, priv);
    priv->gparam = gparam;
    g_param_spec_ref (gparam);

    gjs_debug(GJS_DEBUG_GPARAM,
              "JSObject created with param instance %p type %s",
              priv->gparam, g_type_name(G_TYPE_FROM_INSTANCE((GTypeInstance*) priv->gparam)));

    return obj;
}
Ejemplo n.º 4
0
static void
js_json_emit_jsval(JSContext *cx, jsval value, htsbuf_queue_t *out)
{
  char buf[100];
  if(JSVAL_IS_BOOLEAN(value)) {
    if(JSVAL_TO_BOOLEAN(value))
      htsbuf_append(out, "true", 4);
    else
      htsbuf_append(out, "false", 5);
  } else if(JSVAL_IS_INT(value)) {
    snprintf(buf, sizeof(buf), "%d", JSVAL_TO_INT(value));
    htsbuf_append(out, buf, strlen(buf));
  } else if(JSVAL_IS_DOUBLE(value)) {
    double dbl;
    if(JS_ValueToNumber(cx, value, &dbl) &&
       !my_double2str(buf, sizeof(buf), dbl))
      htsbuf_append(out, buf, strlen(buf));
    else
      htsbuf_append(out, "null", 4);
  } else if(JSVAL_IS_NULL(value)) {
    htsbuf_append(out, "null", 4);
  } else if(JSVAL_IS_STRING(value)) {
    js_json_emit_str(cx, value, out);
  } else if(JSVAL_IS_OBJECT(value)) {
    JSObject *obj = JSVAL_TO_OBJECT(value);
    JSClass *c = JS_GetClass(cx, obj);

    if(!strcmp(c->name, "XML"))   // Treat some classes special
      js_json_emit_str(cx, value, out);
    else {
      if(json_encode_from_object(cx, obj, out))
	htsbuf_append(out, "null", 4);
    }
  }
}
Ejemplo n.º 5
0
static JSBool 
js_item_moveBefore(JSContext *cx, JSObject *obj,
		   uintN argc, jsval *argv, jsval *rval)
{
  js_item_t *ji = JS_GetPrivate(cx, obj);
  js_item_t *before;

  if(argc >= 1 && JSVAL_IS_OBJECT(argv[0]) &&
     !JSVAL_IS_NULL(argv[0]) && 
     JS_GetClass(cx, JSVAL_TO_OBJECT(argv[0])) == &item_class) {
    before = JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0]));
  } else {
    before = NULL;
  }

  TAILQ_REMOVE(&ji->ji_model->jm_items, ji, ji_link);
  if(before)
    TAILQ_INSERT_BEFORE(before, ji, ji_link);
  else
    TAILQ_INSERT_TAIL(&ji->ji_model->jm_items, ji, ji_link);

  prop_move(ji->ji_root, before ? before->ji_root : NULL);
  *rval = JSVAL_VOID;
  return JS_TRUE;
}
Ejemplo n.º 6
0
std::string
gjs_debug_object(JSObject * const obj)
{
    std::ostringstream out;
    const JSClass* clasp = JS_GetClass(obj);
    out << "<object " << clasp->name << " at " << obj <<  '>';
    return out.str();
}
Ejemplo n.º 7
0
void
gjs_define_error_class(JSContext    *context,
                       JSObject     *in_object,
                       GIEnumInfo   *info)
{
    const char *constructor_name;
    GIBoxedInfo *glib_error_info;
    JSObject *prototype, *parent_proto;
    JSObject *constructor;
    Error *priv;

    /* See the comment in gjs_define_boxed_class() for an
     * explanation of how this all works; Error is pretty much the
     * same as Boxed (except that we inherit from GLib.Error).
     */

    constructor_name = g_base_info_get_name( (GIBaseInfo*) info);

    g_irepository_require(NULL, "GLib", "2.0", (GIRepositoryLoadFlags) 0, NULL);
    glib_error_info = (GIBoxedInfo*) g_irepository_find_by_name(NULL, "GLib", "Error");
    parent_proto = gjs_lookup_generic_prototype(context, glib_error_info);
    g_base_info_unref((GIBaseInfo*)glib_error_info);

    if (!gjs_init_class_dynamic(context, in_object,
                                parent_proto,
                                g_base_info_get_namespace( (GIBaseInfo*) info),
                                constructor_name,
                                &gjs_error_class,
                                gjs_error_constructor, 1,
                                /* props of prototype */
                                &gjs_error_proto_props[0],
                                /* funcs of prototype */
                                &gjs_error_proto_funcs[0],
                                /* props of constructor, MyConstructor.myprop */
                                NULL,
                                /* funcs of constructor, MyConstructor.myfunc() */
                                &gjs_error_constructor_funcs[0],
                                &prototype,
                                &constructor)) {
        gjs_log_exception(context);
        g_error("Can't init class %s", constructor_name);
    }

    GJS_INC_COUNTER(gerror);
    priv = g_slice_new0(Error);
    priv->info = info;
    g_base_info_ref( (GIBaseInfo*) priv->info);
    priv->domain = g_quark_from_string (g_enum_info_get_error_domain(priv->info));

    JS_SetPrivate(prototype, priv);

    gjs_debug(GJS_DEBUG_GBOXED, "Defined class %s prototype is %p class %p in object %p",
              constructor_name, prototype, JS_GetClass(prototype), in_object);

    gjs_define_enum_values(context, constructor, priv->info);
    gjs_define_enum_static_methods(context, constructor, priv->info);
}
Ejemplo n.º 8
0
std::string ObjectWrapper::getClassName() {
    auto jsclass = JS_GetClass(_object);

    if (jsclass)
        return jsclass->name;

    JS::RootedValue ctor(_context);
    getValue(InternedString::constructor, &ctor);

    return ObjectWrapper(_context, ctor).getString(InternedString::name);
}
Ejemplo n.º 9
0
bool rs::jsapi::Object::IsObject(const Value& value) {
    auto isObject = value.isObject() && !value.isNull();
    if (isObject) {
        auto obj = value.toObject();
        isObject = obj;
        if (isObject) {
            auto klass = JS_GetClass(obj);
            isObject = klass && klass->name && std::strcmp(klass->name, class_.name) == 0;
        }
    }
    return isObject; 
}
Ejemplo n.º 10
0
JSObject*
gjs_error_from_gerror(JSContext             *context,
                      GError                *gerror,
                      gboolean               add_stack)
{
    JSObject *obj;
    JSObject *proto;
    Error *priv;
    Error *proto_priv;
    GIEnumInfo *info;

    if (gerror == NULL)
        return NULL;

    info = find_error_domain_info(gerror->domain);

    if (!info) {
        /* We don't have error domain metadata */
        /* Marshal the error as a plain GError */
        GIBaseInfo *glib_boxed;
        JSObject *retval;

        glib_boxed = g_irepository_find_by_name(NULL, "GLib", "Error");
        retval = gjs_boxed_from_c_struct(context, glib_boxed, gerror, 0);

        g_base_info_unref(glib_boxed);
        return retval;
    }

    gjs_debug_marshal(GJS_DEBUG_GBOXED,
                      "Wrapping struct %s %p with JSObject",
                      g_base_info_get_name((GIBaseInfo *)info), gboxed);

    proto = gjs_lookup_generic_prototype(context, info);
    proto_priv = priv_from_js(context, proto);

    obj = JS_NewObjectWithGivenProto(context,
                                     JS_GetClass(proto), proto,
                                     gjs_get_import_global (context));

    GJS_INC_COUNTER(gerror);
    priv = g_slice_new0(Error);
    JS_SetPrivate(obj, priv);
    priv->info = info;
    priv->domain = proto_priv->domain;
    g_base_info_ref( (GIBaseInfo*) priv->info);
    priv->gerror = g_error_copy(gerror);

    if (add_stack)
        define_error_properties(context, obj);

    return obj;
}
Ejemplo n.º 11
0
/**
 *  implementation of InstallVersion.compareTo()
 */
static JSBool PR_CALLBACK su_versionCompareTo(JSContext *cx, JSObject *obj, uint argc, jsval *argv, jsval *rval)
{
    int     compval;
    VERSION thisver, v;

    if ( argc == 0 )
        return JS_FALSE;

    if ( JSVAL_IS_STRING(argv[0]) ) {
        su_strToVersion( JS_GetStringBytes(JSVAL_TO_STRING(argv[0])), &v );
    }
    else if (JSVAL_IS_OBJECT(argv[0]) ) {
        /* check to make sure it's an InstallVersion */
        JSObject *argobj;
        JSClass *argclass;

        argobj = JSVAL_TO_OBJECT(argv[0]);
        argclass = JS_GetClass(cx, argobj);

        if ( argclass != &su_version_class ) {
            /* XXX report error here */
            return JS_FALSE;
        }

        su_objToVers( cx, argobj, &v );
    }
    else {
        v.major = v.minor = v.release = v.build = 0;

        if ( argc > 0 && JSVAL_IS_INT(argv[0]) )
            v.major = JSVAL_TO_INT(argv[0]);

        if ( argc > 1 && JSVAL_IS_INT(argv[1]) )
            v.minor = JSVAL_TO_INT(argv[1]);

        if ( argc > 2 && JSVAL_IS_INT(argv[2]) )
            v.release = JSVAL_TO_INT(argv[2]);

        if ( argc > 3 && JSVAL_IS_INT(argv[3]) )
            v.build = JSVAL_TO_INT(argv[3]);
    }

    su_objToVers( cx, obj, &thisver );

    compval = su_compareVersions( &thisver, &v );
    *rval = INT_TO_JSVAL(compval);

    return JS_TRUE;
}
Ejemplo n.º 12
0
bool rs::jsapi::Object::SetPrivate(Value& value, uint64_t data, void* ptr) {
    auto set = false;
    if (value.isObject()) {
        auto obj = value.toObject();
        auto klass = JS_GetClass(obj);
        if (klass != nullptr && std::strcmp(klass->name, Object::class_.name) == 0) {
            auto state = GetState(obj);
            state->data = data;
            state->ptr = ptr;
            set = true;
        }
    }
    
    return set;
}
Ejemplo n.º 13
0
bool rs::jsapi::Object::GetPrivate(const Value& value, uint64_t& data, void*& ptr) {
    auto get = false;
    if (value.isObject()) {
        auto obj = value.toObject();
        auto klass = JS_GetClass(obj);
        if (klass != nullptr && std::strcmp(klass->name, Object::class_.name) == 0) {
            auto state = GetState(obj);
            data = state->data;
            ptr = state->ptr;
            get = true;
        }
    }
    
    return get;
}
Ejemplo n.º 14
0
nsIScriptGlobalObject *
nsWWJSUtils::GetStaticScriptGlobal(JSContext* aContext, JSObject* aObj)
{
  nsISupports* supports;
  JSClass* clazz;
  JSObject* parent;
  JSObject* glob = aObj; // starting point for search

  if (!glob)
    return nsnull;

  while (nsnull != (parent = JS_GetParent(aContext, glob)))
    glob = parent;

#ifdef JS_THREADSAFE
  clazz = JS_GetClass(aContext, glob);
#else
  clazz = JS_GetClass(glob);
#endif

  if (!clazz ||
      !(clazz->flags & JSCLASS_HAS_PRIVATE) ||
      !(clazz->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS) ||
      !(supports = (nsISupports*) JS_GetPrivate(aContext, glob))) {
    return nsnull;
  }
 
  nsCOMPtr<nsIXPConnectWrappedNative> wrapper(do_QueryInterface(supports));
  NS_ENSURE_TRUE(wrapper, nsnull);

  nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryWrappedNative(wrapper));

  // This will return a pointer to something we're about to release,
  // but that's ok here.
  return sgo;
}
Ejemplo n.º 15
0
JSBool
JetpackChild::EvalInSandbox(JSContext* cx, uintN argc, jsval* vp)
{
  if (argc != 2) {
    JS_ReportError(cx, "evalInSandbox takes two arguments");
    return JS_FALSE;
  }

  jsval* argv = JS_ARGV(cx, vp);

  JSObject* obj;
  if (!JSVAL_IS_OBJECT(argv[0]) ||
      !(obj = JSVAL_TO_OBJECT(argv[0]))) {
    JS_ReportError(cx, "The first argument to evalInSandbox must be a global object created using createSandbox.");
    JS_ASSERT(JS_FALSE);
    return JS_FALSE;
  }

  // Unwrap, and switch compartments
  obj = js::UnwrapObject(obj);

  JSAutoEnterCompartment ac;
  if (!ac.enter(cx, obj))
    return JS_FALSE;

  if (&sGlobalClass != JS_GetClass(cx, obj) ||
      obj == JS_GetGlobalObject(cx)) {
    JS_ReportError(cx, "The first argument to evalInSandbox must be a global object created using createSandbox.");
    JS_ASSERT(JS_FALSE);
    return JS_FALSE;
  }

  if (!JS_WrapValue(cx, &argv[1]))
    return JS_FALSE;

  JSString* str = JS_ValueToString(cx, argv[1]);
  if (!str)
    return JS_FALSE;

  size_t length;
  const jschar* chars = JS_GetStringCharsAndLength(cx, str, &length);
  if (!chars)
      return JS_FALSE;

  js::AutoValueRooter ignored(cx);
  return JS_EvaluateUCScript(cx, obj, chars, length, "", 1, ignored.jsval_addr());
}
Ejemplo n.º 16
0
static JSBool getWrappedComponent(JSContext *cx, uintN argc, jsval *argv,
                                  jsval *rval, uint32 slotIndex)
{
  JSObject *wrapped;

  if (!JS_ConvertArguments(cx, argc, argv, "o", &wrapped))
    return JS_FALSE;

  if (JS_GetClass(cx, wrapped) == &sFlexibleWrapper_JSClass.base) {
    if (!JS_GetReservedSlot(cx, wrapped, slotIndex, rval))
      return JS_FALSE;
    return JS_TRUE;
  }

  *rval = JSVAL_NULL;
  return JS_TRUE;
}
Ejemplo n.º 17
0
static bool
constructHook(JSContext *cx, unsigned argc, jsval *vp)
{
    JS::CallArgs args = CallArgsFromVp(argc, vp);

    // Check that arguments were passed properly from JS_New.

    JS::RootedObject obj(cx, JS_NewObject(cx, js::Jsvalify(&JSObject::class_), JS::NullPtr(), JS::NullPtr()));
    if (!obj) {
        JS_ReportError(cx, "test failed, could not construct object");
        return false;
    }
    if (strcmp(JS_GetClass(obj)->name, "Object") != 0) {
        JS_ReportError(cx, "test failed, wrong class for 'this'");
        return false;
    }
    if (args.length() != 3) {
        JS_ReportError(cx, "test failed, argc == %d", args.length());
        return false;
    }
    if (!args[0].isInt32() || args[2].toInt32() != 2) {
        JS_ReportError(cx, "test failed, wrong value in args[2]");
        return false;
    }
    if (!args.isConstructing()) {
        JS_ReportError(cx, "test failed, not constructing");
        return false;
    }

    // Perform a side-effect to indicate that this hook was actually called.
    JS::RootedValue value(cx, args[0]);
    JS::RootedObject callee(cx, &args.callee());
    if (!JS_SetElement(cx, callee, 0, value))
        return false;

    args.rval().setObject(*obj);

    // trash the argv, perversely
    args[0].setUndefined();
    args[1].setUndefined();
    args[2].setUndefined();

    return true;
}
Ejemplo n.º 18
0
nsIScriptGlobalObject *
nsJSUtils::GetStaticScriptGlobal(JSObject* aObj)
{
    const JSClass* clazz;
    JSObject* glob = aObj; // starting point for search

    if (!glob)
        return nullptr;

    glob = js::GetGlobalForObjectCrossCompartment(glob);
    NS_ABORT_IF_FALSE(glob, "Infallible returns null");

    clazz = JS_GetClass(glob);

    // Whenever we end up with globals that are JSCLASS_IS_DOMJSCLASS
    // and have an nsISupports DOM object, we will need to modify this
    // check here.
    MOZ_ASSERT(!(clazz->flags & JSCLASS_IS_DOMJSCLASS));
    nsISupports* supports;
    if (!(clazz->flags & JSCLASS_HAS_PRIVATE) ||
            !(clazz->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS) ||
            !(supports = (nsISupports*)::JS_GetPrivate(glob))) {
        return nullptr;
    }

    // We might either have a window directly (e.g. if the global is a
    // sandbox whose script object principal pointer is a window), or an
    // XPCWrappedNative for a window.  We could also have other
    // sandbox-related script object principals, but we can't do much
    // about those short of trying to walk the proto chain of |glob|
    // looking for a window or something.
    nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryInterface(supports));
    if (!sgo) {
        nsCOMPtr<nsIXPConnectWrappedNative> wrapper(do_QueryInterface(supports));
        if (!wrapper) {
            return nullptr;
        }
        sgo = do_QueryWrappedNative(wrapper);
    }

    // We're returning a pointer to something that's about to be
    // released, but that's ok here.
    return sgo;
}
Ejemplo n.º 19
0
/**
 * focus() - This method puts the focus on this element
 *
 * params - none;
 * return - void
 */
JSBool jhtml_anchor_focus(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
	LOG_HTMLDOM("jhtml_anchor_focus\n");

	if (JS_GetClass(obj) == &JSHtmlAnchorElement)
	{
		HTMLElement *pElem = (HTMLElement *) jhutil_GetPrivate(cx, obj);

		if (!pElem)
		{
			return JS_TRUE;
		}

		pElem->Focus();
	}

	*rval = JSVAL_VOID;
	return JS_TRUE;
}
Ejemplo n.º 20
0
void
js_prop_set_from_jsval(JSContext *cx, prop_t *p, jsval value)
{
  JSBool b;
  if(JSVAL_IS_INT(value)) {
    prop_set_int(p, JSVAL_TO_INT(value));
  } else if(JSVAL_IS_BOOLEAN(value)) {
    prop_set_int(p, JSVAL_TO_BOOLEAN(value));
  } else if(JSVAL_IS_NULL(value) || JSVAL_IS_VOID(value)) {
    prop_set_void(p);
  } else if(JSVAL_IS_DOUBLE(value)) {
    double d;
    if(JS_ValueToNumber(cx, value, &d))
      prop_set_float(p, d);
  } else if(JS_HasInstance(cx, RichText, value, &b) && b) {
    JSObject *o = JSVAL_TO_OBJECT(value);
    jsval v2;

    if(!JS_EnterLocalRootScope(cx))
      return;

    if(!JS_GetProperty(cx, o, "text", &v2)) {
      JS_LeaveLocalRootScope(cx);
      return;
    }

    prop_set_string_ex(p, NULL, JS_GetStringBytes(JS_ValueToString(cx, v2)),
		       PROP_STR_RICH);
    JS_LeaveLocalRootScope(cx);
  } else if(JSVAL_IS_STRING(value)) {
    js_prop_from_str(cx, p, value);
  } else if(JSVAL_IS_OBJECT(value)) {
    JSObject *obj = JSVAL_TO_OBJECT(value);
    JSClass *c = JS_GetClass(cx, obj);

    if(!strcmp(c->name, "XML"))   // Treat some classes special
      js_prop_from_str(cx, p, value);
    else
      js_prop_from_object(cx, obj, p);
  } else {
    prop_set_void(p);
  }
}
Ejemplo n.º 21
0
ComponentJS::ComponentJS(const std::string& scriptFileName)
: _scriptFileName(scriptFileName)
, _jsObj(nullptr)
{
    ScriptingCore* engine = ScriptingCore::getInstance();
    JSContext* cx = engine->getGlobalContext();
    // Require script
    JS::RootedValue classValue(cx);
    _succeedLoadingScript = engine->requireScript(_scriptFileName.c_str(), &classValue);

    if (_succeedLoadingScript)
    {
        JS::RootedObject classObj(cx, classValue.toObjectOrNull());
        const JSClass* theClass = JS_GetClass(classObj);
        JS::RootedValue protoValue(cx);
        JS_GetProperty(cx, classObj, "prototype", &protoValue);

        TypeTest<ComponentJS> t;
        js_type_class_t *typeClass = nullptr;
        std::string typeName = t.s_name();
        auto typeMapIter = _js_global_type_map.find(typeName);
        CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
        typeClass = typeMapIter->second;

        mozilla::Maybe<JS::PersistentRootedObject> *jsObj = new (std::nothrow) mozilla::Maybe<JS::PersistentRootedObject>();

        JS::RootedObject proto(cx, protoValue.toObjectOrNull());
        JS::RootedObject parent(cx, typeClass->proto.ref());
        jsObj->construct(cx);
        JS::RootedObject obj(cx, JS_NewObject(cx, theClass, proto, parent));
        jsObj->ref() = obj;

        // Unbind current proxy binding
        js_proxy_t* jsproxy = js_get_or_create_proxy<ComponentJS>(cx, this);
        JS::RemoveObjectRoot(cx, &jsproxy->obj);
        jsb_remove_proxy(jsproxy);
        // link the native object with the javascript object
        jsb_new_proxy(this, jsObj->ref());

        _jsObj = jsObj;
    }
}
Ejemplo n.º 22
0
static void
ValueToString(JSContext *cx, jsval aJSValue, nsString& aString)
{
	if (JSVAL_IS_VOID(aJSValue)) {
		aString.Assign(kUndefined, STRLEN_ARRAY(kUndefined));
	} else if (JSVAL_IS_NULL(aJSValue)) {
		aString.Assign(kNull, STRLEN_ARRAY(kNull));
	} else if (JSVAL_IS_INT(aJSValue)) {
		jsint i = JSVAL_TO_INT(aJSValue);
		char buf[20];
		PR_snprintf(buf, sizeof(buf), "%d", i);
		aString.Assign(NS_ConvertASCIItoUTF16(buf));
	} else if (JSVAL_IS_DOUBLE(aJSValue)) {
		jsdouble d = JSVAL_TO_DOUBLE(aJSValue);
		char buf[50];
		PR_snprintf(buf, sizeof(buf), "%f", d);
		aString.Assign(NS_ConvertASCIItoUTF16(buf));
	} else if (JSVAL_IS_BOOLEAN(aJSValue)) {
		JSBool b = JSVAL_TO_BOOLEAN(aJSValue);
		if (b)
			aString.Assign(kTrue, STRLEN_ARRAY(kTrue));
		else
			aString.Assign(kFalse, STRLEN_ARRAY(kFalse));
	} else if (JSVAL_IS_STRING(aJSValue)) {
		JSString *str = JSVAL_TO_STRING(aJSValue);
		size_t len;
		const jschar *chars = JS_GetStringCharsAndLength(cx, str, &len);
		NS_ASSERTION(chars, "out of memory");
		if (chars) {
			NS_ASSERTION(sizeof(jschar) == sizeof(PRUnichar),
						 "char size mismatch");
			aString.Assign(reinterpret_cast<const PRUnichar*>(chars), len);
		}
	} else {
		JSObject *obj = JSVAL_TO_OBJECT(aJSValue);
		JSClass *clazz = JS_GetClass(cx, obj);
		aString.Assign(PRUnichar('['));
		aString.Append(NS_ConvertASCIItoUTF16(clazz->name));
		aString.Append(PRUnichar(']'));
	}
}
Ejemplo n.º 23
0
ComponentJS::ComponentJS(const std::string& scriptFileName)
: _scriptFileName(scriptFileName)
, _jsObj(nullptr)
{
    ScriptingCore* engine = ScriptingCore::getInstance();
    JSContext* cx = engine->getGlobalContext();
    // Require script
    JS::RootedValue classValue(cx);
    _succeedLoadingScript = engine->requireScript(_scriptFileName.c_str(), &classValue);
    
    if (_succeedLoadingScript)
    {
        JS::RootedObject classObj(cx, classValue.toObjectOrNull());
        const JSClass* theClass = JS_GetClass(classObj);
        JS::RootedValue protoValue(cx);
        JS_GetProperty(cx, classObj, "prototype", &protoValue);
        
        mozilla::Maybe<JS::PersistentRootedObject> *jsObj = new (std::nothrow) mozilla::Maybe<JS::PersistentRootedObject>();
        
        js_type_class_t *typeClass = js_get_type_from_native<cocos2d::ComponentJS>(this);
        JS::RootedObject proto(cx, protoValue.toObjectOrNull());
        JS::RootedObject parent(cx, typeClass->proto.ref());
        jsObj->construct(cx);
        JS::RootedObject obj(cx, JS_NewObject(cx, theClass, proto, parent));
        jsObj->ref() = obj;
        
        // Unbind current proxy binding
        js_proxy_t* nproxy = jsb_get_native_proxy(this);
        if (nproxy)
        {
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
            JS::RemoveObjectRoot(cx, &nproxy->obj);
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
            jsb_remove_proxy(nproxy, jsb_get_js_proxy(nproxy->obj));
        }
        // link the native object with the javascript object
        jsb_new_proxy(this, jsObj->ref());
        
        _jsObj = jsObj;
    }
}
Ejemplo n.º 24
0
JSBool js_cocos2dx_CCNode_copy(JSContext *cx, uint32_t argc, jsval *vp)
{
	if (argc == 0) {
		JSObject *obj = JS_THIS_OBJECT(cx, vp);
		js_proxy_t *proxy;
		JS_GET_NATIVE_PROXY(proxy, obj);
		cocos2d::CCNode *node = (cocos2d::CCNode *)(proxy ? proxy->ptr : NULL);
		TEST_NATIVE_OBJECT(cx, node)
		JSClass *jsclass = JS_GetClass(obj);
		JSObject *proto = JS_GetPrototype(obj);
		JSObject *parent = JS_GetParent(obj);
		JSObject *jsret = JS_NewObject(cx, jsclass, proto, parent);
		cocos2d::CCObject *ret = node->copy();
		if (ret && jsret) {
			JS_NEW_PROXY(proxy, ret, jsret);
			JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsret));
			return JS_TRUE;
		}
	}
	return JS_FALSE;
}
Ejemplo n.º 25
0
nsIScriptGlobalObject *
nsJSUtils::GetStaticScriptGlobal(JSContext* aContext, JSObject* aObj)
{
  nsISupports* supports;
  JSClass* clazz;
  JSObject* glob = aObj; // starting point for search

  if (!glob)
    return nsnull;

  glob = JS_GetGlobalForObject(aContext, glob);
  NS_ABORT_IF_FALSE(glob, "Infallible returns null");

  clazz = JS_GetClass(glob);

  if (!clazz ||
      !(clazz->flags & JSCLASS_HAS_PRIVATE) ||
      !(clazz->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS) ||
      !(supports = (nsISupports*)::JS_GetPrivate(glob))) {
    return nsnull;
  }

  // We might either have a window directly (e.g. if the global is a
  // sandbox whose script object principal pointer is a window), or an
  // XPCWrappedNative for a window.  We could also have other
  // sandbox-related script object principals, but we can't do much
  // about those short of trying to walk the proto chain of |glob|
  // looking for a window or something.
  nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryInterface(supports));
  if (!sgo) {
    nsCOMPtr<nsIXPConnectWrappedNative> wrapper(do_QueryInterface(supports));
    NS_ENSURE_TRUE(wrapper, nsnull);
    sgo = do_QueryWrappedNative(wrapper);
  }

  // We're returning a pointer to something that's about to be
  // released, but that's ok here.
  return sgo;
}
Ejemplo n.º 26
0
void
gjs_define_param_class(JSContext       *context,
                       JS::HandleObject in_object)
{
    const char *constructor_name;
    JS::RootedObject prototype(context), constructor(context);
    GIObjectInfo *info;

    constructor_name = "ParamSpec";

    if (!gjs_init_class_dynamic(context, in_object, nullptr, "GObject",
                                constructor_name,
                                &gjs_param_class,
                                gjs_param_constructor, 0,
                                /* props of prototype */
                                &gjs_param_proto_props[0],
                                /* funcs of prototype */
                                &gjs_param_proto_funcs[0],
                                /* props of constructor, MyConstructor.myprop */
                                NULL,
                                /* funcs of constructor, MyConstructor.myfunc() */
                                gjs_param_constructor_funcs,
                                &prototype,
                                &constructor)) {
        g_error("Can't init class %s", constructor_name);
    }

    JS::RootedObject gtype_obj(context,
        gjs_gtype_create_gtype_wrapper(context, G_TYPE_PARAM));
    JS_DefineProperty(context, constructor, "$gtype", gtype_obj, JSPROP_PERMANENT);

    info = (GIObjectInfo*)g_irepository_find_by_gtype(g_irepository_get_default(), G_TYPE_PARAM);
    gjs_object_define_static_methods(context, constructor, G_TYPE_PARAM, info);
    g_base_info_unref( (GIBaseInfo*) info);

    gjs_debug(GJS_DEBUG_GPARAM, "Defined class %s prototype is %p class %p in object %p",
              constructor_name, prototype.get(), JS_GetClass(prototype),
              in_object.get());
}
Ejemplo n.º 27
0
JSObject*
gjs_object_from_g_fundamental(JSContext    *context,
                              GIObjectInfo *info,
                              void         *gfundamental)
{
    JSObject *proto;
    JSObject *object;

    if (gfundamental == NULL)
        return NULL;

    object = _fundamental_lookup_object(gfundamental);
    if (object)
        return object;

    gjs_debug_marshal(GJS_DEBUG_GFUNDAMENTAL,
                      "Wrapping fundamental %s.%s %p with JSObject",
                      g_base_info_get_namespace((GIBaseInfo *) info),
                      g_base_info_get_name((GIBaseInfo *) info),
                      gfundamental);

    proto = gjs_lookup_fundamental_prototype_from_gtype(context,
                                                        G_TYPE_FROM_INSTANCE(gfundamental));

    object = JS_NewObjectWithGivenProto(context,
                                        JS_GetClass(proto), proto,
                                        gjs_get_import_global(context));

    if (object == NULL)
        goto out;

    init_fundamental_instance(context, object);

    associate_js_instance_to_fundamental(context, object, gfundamental, FALSE);

 out:
    return object;
}
Ejemplo n.º 28
0
JSBool unwrapAnyObject(JSContext *cx, JSObject *obj, uintN argc,
                       jsval *argv, jsval *rval)
{
  JSObject *wrapped;
  JSObject *wrappee = NULL;

  if (!JS_ConvertArguments(cx, argc, argv, "o", &wrapped))
    return JS_FALSE;

  JSClass *klass = JS_GetClass(cx, wrapped);
  if (klass && (klass->flags & JSCLASS_IS_EXTENDED)) {
    JSExtendedClass *eClass = (JSExtendedClass *) klass;
    if (eClass->wrappedObject != NULL)
      wrappee = eClass->wrappedObject(cx, wrapped);
  }

  if (wrappee)
    *rval = OBJECT_TO_JSVAL(wrappee);
  else
    *rval = JSVAL_NULL;

  return JS_TRUE;
}
Ejemplo n.º 29
0
/**
 * blur - This method removes the focus from this element
 *
 * params - none;
 * return - void;
 */
JSBool jhtml_anchor_blur(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
	LOG_HTMLDOM("jhtml_anchor_blur\n");

	if (JS_GetClass(obj) == &JSHtmlAnchorElement)
	{
		HTMLElement *pElem = (HTMLElement *) jhutil_GetPrivate(cx, obj);

		if (!pElem)
		{
			return JS_TRUE;
		}

		HTMLDocument *pDoc = (pElem)? pElem->GetDocument() : 0;
		if (pDoc && pDoc->Body())
		{
			pDoc->Body()->Focus();
		}
	}

	*rval = JSVAL_VOID;
	return JS_TRUE;
}
Ejemplo n.º 30
0
void
gjs_define_param_class(JSContext    *context,
                       JSObject     *in_object)
{
    const char *constructor_name;
    JSObject *prototype;
    jsval value;
    JSObject *constructor;

    constructor_name = "ParamSpec";

    if (!gjs_init_class_dynamic(context, in_object,
                                NULL,
                                "GObject",
                                constructor_name,
                                &gjs_param_class,
                                gjs_param_constructor, 0,
                                /* props of prototype */
                                &gjs_param_proto_props[0],
                                /* funcs of prototype */
                                &gjs_param_proto_funcs[0],
                                /* props of constructor, MyConstructor.myprop */
                                NULL,
                                /* funcs of constructor, MyConstructor.myfunc() */
                                gjs_param_constructor_funcs,
                                &prototype,
                                &constructor)) {
        g_error("Can't init class %s", constructor_name);
    }

    value = OBJECT_TO_JSVAL(gjs_gtype_create_gtype_wrapper(context, G_TYPE_PARAM));
    JS_DefineProperty(context, constructor, "$gtype", value,
                      NULL, NULL, JSPROP_PERMANENT);

    gjs_debug(GJS_DEBUG_GPARAM, "Defined class %s prototype is %p class %p in object %p",
              constructor_name, prototype, JS_GetClass(prototype), in_object);
}