jsj_jsobject.c

来自「一个基于alice开发的机器人」· C语言 代码 · 共 1,380 行 · 第 1/4 页

C
1,380
字号
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code, released
 * March 31, 1998.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
 
/* This file is part of the Java-vendor-neutral implementation of LiveConnect
 *
 * It contains the implementation of the native methods for the 
 * netscape.javascript.JSObject Java class, which are used for calling into
 * JavaScript from Java.  It also contains the code that handles propagation
 * of exceptions both into and out of Java.
 *
 */

#include <stdlib.h>
#include <string.h>

#include "jsj_private.h"
#include "jsjava.h"

#include "jscntxt.h"        /* For js_ReportErrorAgain().
                               TODO - get rid of private header */

#include "netscape_javascript_JSObject.h"   /* javah-generated headers */


/* A captured JavaScript error, created when JS_ReportError() is called while
   running JavaScript code that is itself called from Java. */
struct CapturedJSError {
    char *              message;
    JSErrorReport       report;         /* Line # of error, etc. */
    jthrowable          java_exception; /* Java exception, error, or null */
    CapturedJSError *   next;           /* Next oldest captured JS error */
};


/*********************** Reflection of JSObjects ****************************/

#ifdef PRESERVE_JSOBJECT_IDENTITY
/*
 * This is a hash table that maps from JS objects to Java objects.
 * It is used to ensure that the same Java object results when a JS
 * object is reflected more than once, so that Java object equality
 * tests work in the expected manner.
 *
 * The entry keys are JSObject pointers and the entry values are Java objects
 * (of type jobject).  When the corresponding Java instance is finalized,
 * the entry is removed from the table, and a JavaScript GC root for the JS
 * object is removed.
 * 
 * This code is disabled because cycles in GC roots between the two systems
 * cause every reflected JS object to become uncollectable.  This can only
 * be solved by using weak links, a feature not available in JDK1.1.
 */
static JSHashTable *js_obj_reflections = NULL;

#ifdef JSJ_THREADSAFE
/*
 * Used to protect the js_obj_reflections hashtable from simultaneous
 * read/write or * write/write access.
 */
static PRMonitor *js_obj_reflections_monitor = NULL;
#endif  /* JSJ_THREADSAFE */
#endif  /* PRESERVE_JSOBJECT_IDENTITY */

JSBool
jsj_init_js_obj_reflections_table()
{
#ifdef PRESERVE_JSOBJECT_IDENTITY
    if(js_obj_reflections != NULL)
    {
      return JS_TRUE;
    }
    js_obj_reflections = JS_NewHashTable(128, NULL, JS_CompareValues,
                                         JS_CompareValues, NULL, NULL);
    if (!js_obj_reflections)
        return JS_FALSE;

#ifdef JSJ_THREADSAFE
    js_obj_reflections_monitor = PR_NewMonitor();
    if (!js_obj_reflections_monitor) {
        JS_HashTableDestroy(js_obj_reflections);
        return JS_FALSE;
    }
#endif  /* JSJ_THREADSAFE */
#endif  /* PRESERVE_JSOBJECT_IDENTITY */

    return JS_TRUE;
}

/*
 * Return a Java object that "wraps" a given JS object by storing the address
 * of the JS object in a private field of the Java object.  A hash table is
 * used to ensure that the mapping of JS objects to Java objects is done on
 * one-to-one basis.
 *
 * If an error occurs, returns NULL and reports an error.
 */

#ifdef PRESERVE_JSOBJECT_IDENTITY

jobject
jsj_WrapJSObject(JSContext *cx, JNIEnv *jEnv, JSObject *js_obj)
{
    jobject java_wrapper_obj;
    JSHashEntry *he, **hep;

    java_wrapper_obj = NULL;

#ifdef JSJ_THREADSAFE
    PR_EnterMonitor(js_obj_reflections_monitor);
#endif

    /* First, look in the hash table for an existing reflection of the same
       JavaScript object.  If one is found, return it. */
    hep = JS_HashTableRawLookup(js_obj_reflections, (JSHashNumber)js_obj, js_obj);

    /* If the same JSObject is reflected into Java more than once then we should
       return the same Java object, both for efficiency and so that the '=='
       operator works as expected in Java when comparing two JSObjects.
       However, it is not possible to hold a reference to a Java object without
       inhibiting GC of that object, at least not in a portable way, i.e.
       a weak reference. So, for now, JSObject identity is broken. */

    he = *hep;
    if (he) {
        java_wrapper_obj = (jobject)he->value;
        JS_ASSERT(java_wrapper_obj);
        if (java_wrapper_obj)
            goto done;
    }

    /* No existing reflection found, so create a new Java object that wraps
       the JavaScript object by storing its address in a private integer field. */
#ifndef OJI
    java_wrapper_obj =
        (*jEnv)->NewObject(jEnv, njJSObject, njJSObject_JSObject, (jint)js_obj);
#else
    if (JSJ_callbacks && JSJ_callbacks->get_java_wrapper != NULL) {
        java_wrapper_obj = JSJ_callbacks->get_java_wrapper(jEnv, (jint)handle);
    }
#endif /*! OJI */

    if (!java_wrapper_obj) {
        jsj_UnexpectedJavaError(cx, jEnv, "Couldn't create new instance of "
                                          "netscape.javascript.JSObject");
        goto done;
    }

    /* Add the new reflection to the hash table. */
    he = JS_HashTableRawAdd(js_obj_reflections, hep, (JSHashNumber)js_obj,
                            js_obj, java_wrapper_obj);
    if (he) {
        /* Tell the JavaScript GC about this object since the only reference
           to it may be in Java-land. */
        JS_AddNamedRoot(cx, (void*)&he->key, "&he->key");
    } else {
        JS_ReportOutOfMemory(cx);
        /* No need to delete java_wrapper_obj because Java GC will reclaim it */
        java_wrapper_obj = NULL;
    }
    
    /*
     * Release local reference to wrapper object, since some JVMs seem reticent
     * about collecting it otherwise.
     */
    /* FIXME -- beard: this seems to make calls into Java with JSObject's fail. */
    /* We should really be creating a global ref if we are putting it in a hash table. */
    /* (*jEnv)->DeleteLocalRef(jEnv, java_wrapper_obj); */

done:
#ifdef JSJ_THREADSAFE
        PR_ExitMonitor(js_obj_reflections_monitor);
#endif
        
    return java_wrapper_obj;
}

/*
 * Remove the mapping of a JS object from the hash table that maps JS objects
 * to Java objects.  This is called from the finalizer of an instance of
 * netscape.javascript.JSObject.
 */
JSBool
jsj_remove_js_obj_reflection_from_hashtable(JSContext *cx, JSObject *js_obj)
{
    JSHashEntry *he, **hep;
    JSBool success = JS_FALSE;

#ifdef JSJ_THREADSAFE
    PR_EnterMonitor(js_obj_reflections_monitor);
#endif

    /* Get the hash-table entry for this wrapper object */
    hep = JS_HashTableRawLookup(js_obj_reflections, (JSHashNumber)js_obj, js_obj);
    he = *hep;

    JS_ASSERT(he);
    if (he) {
        /* Tell the JS GC that Java no longer keeps a reference to this
           JS object. */
        success = JS_RemoveRoot(cx, (void *)&he->key);

        JS_HashTableRawRemove(js_obj_reflections, hep, he);
    }

#ifdef JSJ_THREADSAFE
    PR_ExitMonitor(js_obj_reflections_monitor);
#endif

    return success;
}

#else /* !PRESERVE_JSOBJECT_IDENTITY */


/*
 * The caller must call DeleteLocalRef() on the returned object when no more
 * references remain.
 */
jobject
jsj_WrapJSObject(JSContext *cx, JNIEnv *jEnv, JSObject *js_obj)
{
    jobject java_wrapper_obj;
    JSObjectHandle *handle;

    /* Create a tiny stub object to act as the GC root that points to the
       JSObject from its netscape.javascript.JSObject counterpart. */
    handle = (JSObjectHandle*)JS_malloc(cx, sizeof(JSObjectHandle));
    if (!handle)
        return NULL;
    handle->js_obj = js_obj;
    handle->rt = JS_GetRuntime(cx);

    /* Create a new Java object that wraps the JavaScript object by storing its
       address in a private integer field. */
#ifndef OJI
#if JS_BYTES_PER_LONG == 8
    java_wrapper_obj =
        (*jEnv)->NewObject(jEnv, njJSObject, njJSObject_JSObject, (jlong)handle);
#else
    java_wrapper_obj =
        (*jEnv)->NewObject(jEnv, njJSObject, njJSObject_JSObject, (jint)handle);
#endif
#else
    if (JSJ_callbacks && JSJ_callbacks->get_java_wrapper != NULL) {
        java_wrapper_obj = JSJ_callbacks->get_java_wrapper(jEnv, (jint)handle);
    } else  {
        java_wrapper_obj = NULL;
    }
#endif /*! OJI */
    if (!java_wrapper_obj) {
        jsj_UnexpectedJavaError(cx, jEnv, "Couldn't create new instance of "
                                          "netscape.javascript.JSObject");
        goto done;
    }
 
    JS_AddNamedRoot(cx, &handle->js_obj, "&handle->js_obj");

done:
        
    return java_wrapper_obj;
}

JSObject *
jsj_UnwrapJSObjectWrapper(JNIEnv *jEnv, jobject java_wrapper_obj)
{
    JSObjectHandle *handle;

#ifndef OJI
#if JS_BYTES_PER_LONG == 8
    handle = (JSObjectHandle*)((*jEnv)->GetLongField(jEnv, java_wrapper_obj, njJSObject_long_internal));
#else
    handle = (JSObjectHandle*)((*jEnv)->GetIntField(jEnv, java_wrapper_obj, njJSObject_internal));
#endif
#else
    /* Unwrapping this wrapper requires knowledge of the structure of the object. This is privileged
       information that only the object implementor can know. In this case the object implementor
       is the java plugin (such as the Sun plugin class sun.plugin.javascript.navig5.JSObject. 
	   Since the plugin owns this structure, we defer to it to unwrap the object. If the plugin 
	   does not implement this callback, then it should be set to null. In that case we try something 
	   that works with Sun's plugin assuming that it has not yet been implemented yet. This 'else' 
	   case should be removed as soon as the unwrap function is supported by the Sun JPI. */

    if (JSJ_callbacks && JSJ_callbacks->unwrap_java_wrapper != NULL) {
        handle = (JSObjectHandle*)JSJ_callbacks->unwrap_java_wrapper(jEnv, java_wrapper_obj);
    }
    else {
        jclass   cid = (*jEnv)->GetObjectClass(jEnv, java_wrapper_obj);
        jfieldID fid = (*jEnv)->GetFieldID(jEnv, cid, "nativeJSObject", "I");
        handle = (JSObjectHandle*)((*jEnv)->GetIntField(jEnv, java_wrapper_obj, fid));
    }
#endif
    
	/* JNI returns a NULL handle for a Java 'null' */
    if (!handle)
        return NULL;

    return handle->js_obj;
	
}

#endif  /* !PRESERVE_JSOBJECT_IDENTITY */

/*************** Handling of Java exceptions in JavaScript ******************/

/*
 * Free up a JavaScript error that has been stored by the
 * capture_js_error_reports_for_java() function.
 */
static CapturedJSError *

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?