Пример #1
0
static JSBool
gjs_value_from_g_value_internal(JSContext    *context,
                                jsval        *value_p,
                                const GValue *gvalue,
                                gboolean      no_copy,
                                GSignalQuery *signal_query,
                                gint          arg_n)
{
    GType gtype;

    gtype = G_VALUE_TYPE(gvalue);

    gjs_debug_marshal(GJS_DEBUG_GCLOSURE,
                      "Converting gtype %s to jsval",
                      g_type_name(gtype));

    if (gtype == G_TYPE_STRING) {
        const char *v;
        v = g_value_get_string(gvalue);
        if (v == NULL) {
            gjs_debug_marshal(GJS_DEBUG_GCLOSURE,
                              "Converting NULL string to JSVAL_NULL");
            *value_p = JSVAL_NULL;
        } else {
            if (!gjs_string_from_utf8(context, v, -1, value_p))
                return JS_FALSE;
        }
    } else if (gtype == G_TYPE_CHAR) {
        char v;
        v = g_value_get_schar(gvalue);
        *value_p = INT_TO_JSVAL(v);
    } else if (gtype == G_TYPE_UCHAR) {
        unsigned char v;
        v = g_value_get_uchar(gvalue);
        *value_p = INT_TO_JSVAL(v);
    } else if (gtype == G_TYPE_INT) {
        int v;
        v = g_value_get_int(gvalue);
        return JS_NewNumberValue(context, v, value_p);
    } else if (gtype == G_TYPE_UINT) {
        uint v;
        v = g_value_get_uint(gvalue);
        return JS_NewNumberValue(context, v, value_p);
    } else if (gtype == G_TYPE_DOUBLE) {
        double d;
        d = g_value_get_double(gvalue);
        return JS_NewNumberValue(context, d, value_p);
    } else if (gtype == G_TYPE_FLOAT) {
        double d;
        d = g_value_get_float(gvalue);
        return JS_NewNumberValue(context, d, value_p);
    } else if (gtype == G_TYPE_BOOLEAN) {
        gboolean v;
        v = g_value_get_boolean(gvalue);
        *value_p = BOOLEAN_TO_JSVAL(v);
    } else if (g_type_is_a(gtype, G_TYPE_OBJECT) || g_type_is_a(gtype, G_TYPE_INTERFACE)) {
        GObject *gobj;
        JSObject *obj;

        gobj = g_value_get_object(gvalue);

        obj = gjs_object_from_g_object(context, gobj);
        *value_p = OBJECT_TO_JSVAL(obj);
    } else if (gtype == G_TYPE_STRV) {
        if (!gjs_array_from_strv (context,
                                  value_p,
                                  g_value_get_boxed (gvalue))) {
            gjs_throw(context, "Failed to convert strv to array");
            return JS_FALSE;
        }
    } else if (g_type_is_a(gtype, G_TYPE_HASH_TABLE) ||
               g_type_is_a(gtype, G_TYPE_ARRAY) ||
               g_type_is_a(gtype, G_TYPE_BYTE_ARRAY) ||
               g_type_is_a(gtype, G_TYPE_PTR_ARRAY)) {
        gjs_throw(context,
                  "Unable to introspect element-type of container in GValue");
        return JS_FALSE;
    } else if (g_type_is_a(gtype, G_TYPE_BOXED) ||
               g_type_is_a(gtype, G_TYPE_VARIANT)) {
        GjsBoxedCreationFlags boxed_flags;
        GIBaseInfo *info;
        void *gboxed;
        JSObject *obj;

        if (g_type_is_a(gtype, G_TYPE_BOXED))
            gboxed = g_value_get_boxed(gvalue);
        else
            gboxed = g_value_get_variant(gvalue);
        boxed_flags = GJS_BOXED_CREATION_NONE;

        /* special case GError */
        if (g_type_is_a(gtype, G_TYPE_ERROR)) {
            obj = gjs_error_from_gerror(context, gboxed, FALSE);
            *value_p = OBJECT_TO_JSVAL(obj);

            return TRUE;
        }

        /* The only way to differentiate unions and structs is from
         * their g-i info as both GBoxed */
        info = g_irepository_find_by_gtype(g_irepository_get_default(),
                                           gtype);
        if (info == NULL) {
            gjs_throw(context,
                      "No introspection information found for %s",
                      g_type_name(gtype));
            return JS_FALSE;
        }

        if (g_base_info_get_type(info) == GI_INFO_TYPE_STRUCT &&
            g_struct_info_is_foreign((GIStructInfo*)info)) {
            JSBool ret;
            GIArgument arg;
            arg.v_pointer = gboxed;
            ret = gjs_struct_foreign_convert_from_g_argument(context, value_p, info, &arg);
            g_base_info_unref(info);
            return ret;
        }

        switch (g_base_info_get_type(info)) {
        case GI_INFO_TYPE_BOXED:
        case GI_INFO_TYPE_STRUCT:
            if (no_copy)
                boxed_flags |= GJS_BOXED_CREATION_NO_COPY;
            obj = gjs_boxed_from_c_struct(context, (GIStructInfo *)info, gboxed, boxed_flags);
            break;
        case GI_INFO_TYPE_UNION:
            obj = gjs_union_from_c_union(context, (GIUnionInfo *)info, gboxed);
            break;
        default:
            gjs_throw(context,
                      "Unexpected introspection type %d for %s",
                      g_base_info_get_type(info),
                      g_type_name(gtype));
            g_base_info_unref(info);
            return JS_FALSE;
        }

        *value_p = OBJECT_TO_JSVAL(obj);
        g_base_info_unref(info);
    } else if (g_type_is_a(gtype, G_TYPE_ENUM)) {
        return convert_int_to_enum(context, value_p, gtype, g_value_get_enum(gvalue));
    } else if (g_type_is_a(gtype, G_TYPE_PARAM)) {
        GParamSpec *gparam;
        JSObject *obj;

        gparam = g_value_get_param(gvalue);

        obj = gjs_param_from_g_param(context, gparam);
        *value_p = OBJECT_TO_JSVAL(obj);
    } else if (signal_query && g_type_is_a(gtype, G_TYPE_POINTER)) {
        JSBool res;
        GArgument arg;
        GIArgInfo *arg_info;
        GIBaseInfo *obj;
        GISignalInfo *signal_info;
        GITypeInfo type_info;

        obj = g_irepository_find_by_gtype(NULL, signal_query->itype);
        if (!obj) {
            gjs_throw(context, "Signal argument with GType %s isn't introspectable",
                      g_type_name(signal_query->itype));
            return JS_FALSE;
        }

        signal_info = g_object_info_find_signal((GIObjectInfo*)obj, signal_query->signal_name);

        if (!signal_info) {
            gjs_throw(context, "Unknown signal.");
            g_base_info_unref((GIBaseInfo*)obj);
            return JS_FALSE;
        }
        arg_info = g_callable_info_get_arg(signal_info, arg_n - 1);
        g_arg_info_load_type(arg_info, &type_info);

        arg.v_pointer = g_value_get_pointer(gvalue);

        res = gjs_value_from_g_argument(context, value_p, &type_info, &arg, TRUE);

        g_base_info_unref((GIBaseInfo*)arg_info);
        g_base_info_unref((GIBaseInfo*)signal_info);
        g_base_info_unref((GIBaseInfo*)obj);
        return res;
    } else if (g_type_is_a(gtype, G_TYPE_POINTER)) {
        gpointer pointer;

        pointer = g_value_get_pointer(gvalue);

        if (pointer == NULL) {
            *value_p = JSVAL_NULL;
        } else {
            gjs_throw(context,
                      "Can't convert non-null pointer to JS value");
            return JS_FALSE;
        }
    } else if (g_value_type_transformable(gtype, G_TYPE_DOUBLE)) {
        GValue double_value = { 0, };
        double v;
        g_value_init(&double_value, G_TYPE_DOUBLE);
        g_value_transform(gvalue, &double_value);
        v = g_value_get_double(&double_value);
        return JS_NewNumberValue(context, v, value_p);
    } else if (g_value_type_transformable(gtype, G_TYPE_INT)) {
        GValue int_value = { 0, };
        int v;
        g_value_init(&int_value, G_TYPE_INT);
        g_value_transform(gvalue, &int_value);
        v = g_value_get_int(&int_value);
        return JS_NewNumberValue(context, v, value_p);
    } else {
        gjs_throw(context,
                  "Don't know how to convert GType %s to JavaScript object",
                  g_type_name(gtype));
        return JS_FALSE;
    }

    return JS_TRUE;
}
Пример #2
0
INT unit_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{	
	CDebug cDbg("unit getProperty");

	BnetData* pData = *p_D2LAUNCH_BnData;
	GameStructInfo* pInfo = *p_D2CLIENT_GameInfo;

	switch(JSVAL_TO_INT(id))
	{
		case ME_ACCOUNT:
			if(!pData)
				return JS_TRUE;
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szAccountName));
			break;
		case ME_CHARNAME:
			if(!pInfo)
				return JS_TRUE;
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szCharName));
			break;
		case ME_CHICKENHP:
			*vp = INT_TO_JSVAL(Vars.nChickenHP);
			break;
		case ME_CHICKENMP:
			*vp = INT_TO_JSVAL(Vars.nChickenMP);
			break;
		case ME_DIFF:
			*vp = INT_TO_JSVAL(D2CLIENT_GetDifficulty());
			break;
		case ME_GAMENAME:
			if(!pInfo)
				return JS_TRUE;
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGameName));
			break;
		case ME_GAMEPASSWORD:
			if(!pInfo)
				return JS_TRUE;
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGamePassword));
			break;
		case ME_GAMESERVERIP:
			if(!pInfo)
				return JS_TRUE;
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGameServerIp));
			break;
		case ME_GAMESTARTTIME:
			*vp = INT_TO_JSVAL(Vars.dwGameTime);
			break;
		case ME_GAMETYPE:
			*vp = INT_TO_JSVAL(*p_D2CLIENT_ExpCharFlag);
			break;
		case ME_ITEMONCURSOR:
			*vp = BOOLEAN_TO_JSVAL(!!D2CLIENT_GetCursorItem());
			break;
		case ME_LADDER:
			if(pData)
				*vp = BOOLEAN_TO_JSVAL(((pData->nCharFlags & PLAYER_TYPE_LADDER) == TRUE));
			break;
		case ME_QUITONHOSTILE:
			*vp = BOOLEAN_TO_JSVAL(Vars.bQuitOnHostile);
			break;
		case ME_REALM:
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szRealmName));
			break;
		case ME_REALMSHORT:
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szRealmName2));
			break;
		case OOG_SCREENSIZE:
			*vp = INT_TO_JSVAL(D2GFX_GetScreenSize());
			break;
		case OOG_WINDOWTITLE:
			CHAR szTitle[128];
			GetWindowText(D2WIN_GetHwnd(), szTitle, 128);
			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szTitle));
			break;
		case ME_PING:
			*vp = INT_TO_JSVAL(*p_D2CLIENT_Ping);
			break;
		case OOG_INGAME:
			*vp = BOOLEAN_TO_JSVAL(ClientState() == ClientStateMenu ? FALSE : TRUE);
			break;
		case OOG_QUITONERROR:
			*vp = BOOLEAN_TO_JSVAL(Vars.bQuitOnError);
			break;
		case OOG_MAXGAMETIME:
			*vp = INT_TO_JSVAL(Vars.dwMaxGameTime);
			break;
		case OOG_DEBUG:
			*vp = BOOLEAN_TO_JSVAL(Vars.bDebug);
			break;
		case ME_MERCREVIVECOST:
			*vp = INT_TO_JSVAL((*p_D2CLIENT_MercReviveCost));
			break;
		case ME_BLOCKKEYS:
			*vp = BOOLEAN_TO_JSVAL(Vars.bBlockKeys);
			break;
		case ME_BLOCKMOUSE:
			*vp = BOOLEAN_TO_JSVAL(Vars.bBlockMouse);
			break;
		default:
			break;
	}

/*
	// TODO: Properly fix this...
	if ((JSVAL_TO_INT(id) < OOG_WINDOWTITLE) && !GameReady())
			return JS_TRUE;
*/
	if(!GameReady())
		return JS_TRUE;

	myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj);

	if(!lpUnit || IsBadReadPtr(lpUnit, sizeof(myUnit)) || lpUnit->_dwPrivateType != PRIVATE_UNIT)
		return JS_TRUE;

	UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType);

	if(!pUnit)
		return JS_TRUE;

	char* tmp = NULL;
	Room1* pRoom = NULL;

	switch(JSVAL_TO_INT(id))
	{
		case UNIT_TYPE:
			*vp = INT_TO_JSVAL(pUnit->dwType);
			break;
		case UNIT_CLASSID:
			*vp = INT_TO_JSVAL(pUnit->dwTxtFileNo);
			break;
		case UNIT_MODE:
			*vp = INT_TO_JSVAL(pUnit->dwMode);
			break;
		case UNIT_NAME:
			tmp = new char[8192];
			GetUnitName(pUnit, tmp, 8192);
			*vp = STRING_TO_JSVAL(JS_InternString(cx, tmp));
			delete[] tmp;
			break;
		case UNIT_ACT:
			*vp = INT_TO_JSVAL(pUnit->dwAct + 1);
			break;
		case UNIT_AREA:
			pRoom = D2COMMON_GetRoomFromUnit(pUnit);
			if(pRoom && pRoom->pRoom2 && pRoom->pRoom2->pLevel)
				*vp = INT_TO_JSVAL(pRoom->pRoom2->pLevel->dwLevelNo);			
			break;
		case UNIT_ID:
			*vp = INT_TO_JSVAL(pUnit->dwUnitId);
			break;
		case UNIT_XPOS:
			*vp = INT_TO_JSVAL(GetUnitX(pUnit));
			break;
		case UNIT_YPOS:
			*vp = INT_TO_JSVAL(GetUnitY(pUnit));
			break;
		case UNIT_HP:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 6, 0) >> 8);
			break;
		case UNIT_HPMAX:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 7, 0) >> 8);
			break;
		case UNIT_MP:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 8, 0) >> 8);
			break;
		case UNIT_MPMAX:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 9, 0) >> 8);
			break;
		case UNIT_STAMINA:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 10, 0) >> 8);
			break;
		case UNIT_STAMINAMAX:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 11, 0) >> 8);
			break;
		case UNIT_CHARLVL:
			*vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 12, 0));
			break;
		case ME_RUNWALK:
			*vp = INT_TO_JSVAL(*p_D2CLIENT_AlwaysRun);
			break;
		case UNIT_ADDRESS:
			*vp = INT_TO_JSVAL(pUnit);
			break;
		case UNIT_SPECTYPE:
			DWORD SpecType;
			SpecType = NULL;
			if(pUnit->dwType == UNIT_MONSTER && pUnit->pMonsterData)
			{
				if(pUnit->pMonsterData->fMinion & 1)
					SpecType |= 0x08;
				if(pUnit->pMonsterData->fBoss & 1)
					SpecType |= 0x04;
				if(pUnit->pMonsterData->fChamp & 1)
					SpecType |= 0x02;
				if((pUnit->pMonsterData->fBoss & 1)&& (pUnit->pMonsterData->fNormal & 1))
					SpecType |= 0x01;
				if(pUnit->pMonsterData->fNormal & 1)
					SpecType |= 0x00;
				*vp = INT_TO_JSVAL(SpecType);
				return JS_TRUE;
			}
			break;
		case UNIT_UNIQUEID:
			if(pUnit->dwType == UNIT_MONSTER && pUnit->pMonsterData->fBoss && pUnit->pMonsterData->fNormal)
				*vp = INT_TO_JSVAL(pUnit->pMonsterData->wUniqueNo);
			else
				*vp = INT_TO_JSVAL(-1);
			break;
		case ITEM_CODE: // replace with better method if found
			if(!(pUnit->dwType == UNIT_ITEM) && pUnit->pItemData)
				break;
			ItemTxt* pTxt;
			pTxt = D2COMMON_GetItemText(pUnit->dwTxtFileNo);
			if(!pTxt) {
				*vp = STRING_TO_JSVAL(JS_InternString(cx, "Unknown"));
				return JS_TRUE;
			}
			CHAR szCode[4];
			memcpy(szCode, pTxt->szCode, 3);
			szCode[3] = 0x00;
			*vp = STRING_TO_JSVAL(JS_InternString(cx, szCode));
			break;
		case ITEM_PREFIX:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
				if (D2COMMON_GetItemMagicalMods(pUnit->pItemData->wPrefix))
					*vp = STRING_TO_JSVAL(JS_InternString(cx, D2COMMON_GetItemMagicalMods(pUnit->pItemData->wPrefix)));
			break;
			
		case ITEM_SUFFIX:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
				if (D2COMMON_GetItemMagicalMods(pUnit->pItemData->wSuffix))
					*vp = STRING_TO_JSVAL(JS_InternString(cx, D2COMMON_GetItemMagicalMods(pUnit->pItemData->wSuffix)));
			break;
		case ITEM_PREFIXNUM:
				if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
					*vp = INT_TO_JSVAL(pUnit->pItemData->wPrefix);
			break;
		case ITEM_SUFFIXNUM:
				if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
					*vp = INT_TO_JSVAL(pUnit->pItemData->wSuffix);
			break;
		case ITEM_FNAME:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) {
				wchar_t wszfname[256] = L"";
				D2CLIENT_GetItemName(pUnit, wszfname, sizeof(wszfname));
				if(wszfname) {
					char* tmp = UnicodeToAnsi(wszfname);
					*vp = STRING_TO_JSVAL(JS_InternString(cx, tmp));
					delete[] tmp;
				}
			}
			break;
		case ITEM_QUALITY:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
				*vp = INT_TO_JSVAL(pUnit->pItemData->dwQuality);
			break;
		case ITEM_NODE:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
				*vp = INT_TO_JSVAL(pUnit->pItemData->NodePage);
			break;
		case ITEM_LOC:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData)
				*vp = INT_TO_JSVAL(pUnit->pItemData->ItemLocation);
			break;
		case ITEM_SIZEX:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) {
				if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo))
					break;
				*vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->xSize);
			}
			break;
		case ITEM_SIZEY:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) {
				if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo))
					break;
				*vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->ySize);
			}
			break;
		case ITEM_Type:
			if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) {
				if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo))
					break;
				*vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->nType);
			}
			break;
		case ITEM_DESC:
			{
			if(pUnit->dwType != UNIT_ITEM)
				break;

				wchar_t wBuffer[8192] = L"";
				D2CLIENT_GetItemDesc(pUnit, wBuffer);
				tmp = UnicodeToAnsi(wBuffer);
				*vp = STRING_TO_JSVAL(JS_InternString(cx, tmp));
				delete[] tmp;
			}
			break;
		case UNIT_ITEMCOUNT:
			if(pUnit->pInventory)
				*vp = INT_TO_JSVAL(pUnit->pInventory->dwItemCount);
			break;
		case ITEM_BODYLOCATION:
			if(pUnit->dwType != UNIT_ITEM)
				break;
			if(pUnit->pItemData)
				*vp = INT_TO_JSVAL(pUnit->pItemData->BodyLocation);
			break;
		case UNIT_OWNER:
			*vp = INT_TO_JSVAL(pUnit->dwOwnerId);
			break;
		case UNIT_OWNERTYPE:
			*vp = INT_TO_JSVAL(pUnit->dwOwnerType);
			break;
		case ITEM_LEVEL:
			if(pUnit->dwType != UNIT_ITEM)
				break;
			if(pUnit->pItemData)
				*vp = INT_TO_JSVAL(pUnit->pItemData->dwItemLevel);
			break;
		case ITEM_LEVELREQ:
			if(pUnit->dwType != UNIT_ITEM)
				break;
			*vp = INT_TO_JSVAL(D2COMMON_GetItemLevelRequirement(pUnit, D2CLIENT_GetPlayerUnit()));
			break;
		case UNIT_DIRECTION:
			if(pUnit->pPath)
				*vp = INT_TO_JSVAL(pUnit->pPath->bDirection);
			break;
		case OBJECT_TYPE:
			if(pUnit->dwType == UNIT_OBJECT)
				if(pUnit->pObjectData)
				{
					pRoom = D2COMMON_GetRoomFromUnit(pUnit);
					if(pRoom && pRoom->pRoom2 && pRoom->pRoom2->pLevel && IsTownLevel(pRoom->pRoom2->pLevel->dwLevelNo))
						*vp = INT_TO_JSVAL(pUnit->pObjectData->Type & 255);
					else
						*vp = INT_TO_JSVAL(pUnit->pObjectData->Type);
				}
			break;
		case ME_WSWITCH:
			*vp = INT_TO_JSVAL(*p_D2CLIENT_bWeapSwitch);
			break;
		default:
			break;
	}

	return JS_TRUE;
}
Пример #3
0
static JSBool js_get(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
	jsval idval;
    jsint		tiny;
	jsrefcount	rc;

    JS_IdToValue(cx, id, &idval);
    tiny = JSVAL_TO_INT(idval);

	rc=JS_SUSPENDREQUEST(cx);
	switch(tiny) {
		case PROP_WSCROLL:
			*vp=BOOLEAN_TO_JSVAL(_wscroll);
			break;
		case PROP_DIRECTVIDEO:
			*vp=BOOLEAN_TO_JSVAL(directvideo);
			break;
		case PROP_HOLD_UPDATE:
			*vp=BOOLEAN_TO_JSVAL(hold_update);
			break;
		case PROP_PUTTEXT_CAN_MOVE:
			*vp=BOOLEAN_TO_JSVAL(puttext_can_move);
			break;
		case PROP_MODE:
			*vp=INT_TO_JSVAL(cio_api.mode);
			break;
		case PROP_MOUSE:
			*vp=BOOLEAN_TO_JSVAL(cio_api.mouse);
			break;
		case PROP_ESCDELAY:
			*vp=INT_TO_JSVAL(cio_api.ESCDELAY?*cio_api.ESCDELAY:0);
			break;
		case PROP_TEXTATTR:
			*vp=INT_TO_JSVAL(cio_textinfo.attribute);
			break;
		case PROP_KBHIT:
			*vp=BOOLEAN_TO_JSVAL(kbhit());
			break;
		case PROP_WHEREX:
			*vp=INT_TO_JSVAL(cio_textinfo.curx);
			break;
		case PROP_WHEREY:
			*vp=INT_TO_JSVAL(cio_textinfo.cury);
			break;
		case PROP_TEXTMODE:
			*vp=INT_TO_JSVAL(cio_textinfo.currmode);
			break;
		case PROP_WINLEFT:
			*vp=INT_TO_JSVAL(cio_textinfo.winleft);
			break;
		case PROP_WINTOP:
			*vp=INT_TO_JSVAL(cio_textinfo.wintop);
			break;
		case PROP_WINRIGHT:
			*vp=INT_TO_JSVAL(cio_textinfo.winright);
			break;
		case PROP_WINBOTTOM:
			*vp=INT_TO_JSVAL(cio_textinfo.winbottom);
			break;
		case PROP_SCREENWIDTH:
			*vp=INT_TO_JSVAL(cio_textinfo.screenwidth);
			break;
		case PROP_SCREENHEIGHT:
			*vp=INT_TO_JSVAL(cio_textinfo.screenheight);
			break;
		case PROP_NORMATTR:
			*vp=INT_TO_JSVAL(cio_textinfo.normattr);
			break;
		case PROP_TEXTBACKGROUND:
			*vp=INT_TO_JSVAL((cio_textinfo.attribute & 0x70)>>4);
			break;
		case PROP_TEXTCOLOR:
			*vp=INT_TO_JSVAL(cio_textinfo.attribute & 0xf);
			break;
		case PROP_CLIPBOARD:
			*vp=STRING_TO_JSVAL(JS_NewStringCopyZ(cx,getcliptext()));
			break;
		case PROP_HIGHVIDEO:
			*vp=BOOLEAN_TO_JSVAL(cio_textinfo.attribute & 0x8);
			break;
		case PROP_LOWVIDEO:
			*vp=BOOLEAN_TO_JSVAL(!(cio_textinfo.attribute & 0x8));
			break;
	}
	JS_RESUMEREQUEST(cx, rc);

	return(JS_TRUE);
}
Пример #4
0
static JSBool
js_conio_puttext(JSContext *cx, uintN argc, jsval *arglist)
{
	jsval *argv=JS_ARGV(cx, arglist);
	int32	args[4];
	unsigned char	*buffer;
	jsuint	i;
	int32	j;
	jsuint	size;
	jsval	val;
	JSObject *array;
	jsrefcount	rc;

	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	/* default values: */
	args[0]=1;
	args[1]=1;
	args[2]=cio_textinfo.screenwidth;
	args[3]=cio_textinfo.screenheight;

	if(argc != 5)
		return(JS_FALSE);
	for(i=0; i<4; i++) {
		if(!JSVAL_IS_NUMBER(argv[i]))
			return(JS_FALSE);
		if(!JS_ValueToInt32(cx, argv[i], &args[i]))
			return(JS_FALSE);
	}
	if(args[0] < 1 || args[1] < 1 || args[2] < 1 || args[3] < 1
			|| args[0] > args[2] || args[1] > args[3]
			|| args[2] > cio_textinfo.screenwidth || args[3] > cio_textinfo.screenheight) {
		JS_SET_RVAL(cx, arglist,JSVAL_FALSE);
		return(JS_TRUE);
	}

	if(!JSVAL_IS_OBJECT(argv[4]))
		return(JS_FALSE);
	array=JSVAL_TO_OBJECT(argv[4]);
	if(!JS_GetArrayLength(cx, array, &size))
		return(JS_FALSE);

	buffer=(unsigned char *)malloc(size);
	if(buffer==NULL) 
		return(JS_FALSE);
	for(i=0; i<size; i++) {
		if(!JS_GetElement(cx, array, i, &val)) {
			free(buffer);
			return(JS_FALSE);
		}
		if(!JSVAL_IS_NUMBER(val)) {
			free(buffer);
			return(JS_FALSE);
		}
		if(!JS_ValueToInt32(cx, val, &j)) {
			free(buffer);
			return(JS_FALSE);
		}
		buffer[i]=(unsigned char)j;
	}

	rc=JS_SUSPENDREQUEST(cx);
	JS_SET_RVAL(cx, arglist,BOOLEAN_TO_JSVAL(puttext(args[0], args[1], args[2], args[3], buffer)));
	free(buffer);
	JS_RESUMEREQUEST(cx, rc);
	return(JS_TRUE);
}
Пример #5
0
JSBool js_game_setting_get_multiplayer(JSContext *cx,JSObject *j_obj,jsval id,jsval *vp)
{
	*vp=BOOLEAN_TO_JSVAL(net_setup.client.joined);
	return(JS_TRUE);
}
//
// Native method InstallChrome
//
static JSBool
InstallTriggerGlobalInstallChrome(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  nsIDOMInstallTriggerGlobal *nativeThis = getTriggerNative(cx, obj);
  if (!nativeThis)
    return JS_FALSE;

  uint32       chromeType = NOT_CHROME;
  nsAutoString sourceURL;
  nsAutoString name;

  *rval = JSVAL_FALSE;

  // get chromeType first, the update enabled check for skins skips whitelisting
  if (argc >=1)
  {
      if (!JS_ValueToECMAUint32(cx, argv[0], &chromeType))
          return JS_FALSE;
  }

  // make sure XPInstall is enabled, return if not
  nsIScriptGlobalObject *globalObject = nsnull;
  nsIScriptContext *scriptContext = GetScriptContextFromJSContext(cx);
  if (scriptContext)
      globalObject = scriptContext->GetGlobalObject();

  if (!globalObject)
      return JS_TRUE;

  // get window.location to construct relative URLs
  nsCOMPtr<nsIURI> baseURL;
  JSObject* global = JS_GetGlobalObject(cx);
  if (global)
  {
    jsval v;
    if (JS_GetProperty(cx,global,"location",&v))
    {
      nsAutoString location;
      ConvertJSValToStr( location, cx, v );
      NS_NewURI(getter_AddRefs(baseURL), location);
    }
  }


  if ( argc >= 3 )
  {
    ConvertJSValToStr(sourceURL, cx, argv[1]);
    ConvertJSValToStr(name, cx, argv[2]);

    if (baseURL)
    {
        nsCAutoString resolvedURL;
        baseURL->Resolve(NS_ConvertUTF16toUTF8(sourceURL), resolvedURL);
        sourceURL = NS_ConvertUTF8toUTF16(resolvedURL);
    }

    // Make sure caller is allowed to load this url.
    nsresult rv = InstallTriggerCheckLoadURIFromScript(cx, sourceURL);
    if (NS_FAILED(rv))
        return JS_FALSE;

    if ( chromeType & CHROME_ALL )
    {
        // there's at least one known chrome type
        nsCOMPtr<nsIURI> checkuri;
        nsresult rv = nativeThis->GetOriginatingURI(globalObject,
                                                    getter_AddRefs(checkuri));
        if (NS_SUCCEEDED(rv))
        {
            nsAutoPtr<nsXPITriggerInfo> trigger(new nsXPITriggerInfo());
            nsAutoPtr<nsXPITriggerItem> item(new nsXPITriggerItem(name.get(),
                                                                  sourceURL.get(),
                                                                  nsnull));
            if (trigger && item)
            {
                // trigger will free item when complete
                trigger->Add(item.forget());
                nsCOMPtr<nsIDOMWindowInternal> win(do_QueryInterface(globalObject));
                nsCOMPtr<nsIXPIInstallInfo> installInfo =
                    new nsXPIInstallInfo(win, checkuri, trigger, chromeType);
                if (installInfo)
                {
                    // installInfo owns trigger now
                    trigger.forget();
                    PRBool enabled = PR_FALSE;
                    nativeThis->UpdateEnabled(checkuri, XPI_WHITELIST,
                                              &enabled);
                    if (!enabled)
                    {
                        nsCOMPtr<nsIObserverService> os =
                          mozilla::services::GetObserverService();
                        if (os)
                            os->NotifyObservers(installInfo,
                                                "xpinstall-install-blocked",
                                                nsnull);
                    }
                    else
                    {
                        PRBool nativeRet = PR_FALSE;
                        nativeThis->StartInstall(installInfo, &nativeRet);
                        *rval = BOOLEAN_TO_JSVAL(nativeRet);
                    }
                }
            }
        }
    }
  }
  return JS_TRUE;
}
Пример #7
0
static JSBool js_get(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
    jsint			tiny;
    js_branch_t*	branch;

    if((branch=(js_branch_t*)JS_GetPrivate(cx,obj))==NULL)
        return(JS_FALSE);

    tiny = JSVAL_TO_INT(id);

    switch(tiny) {
    case PROP_VERSION:
        *vp=STRING_TO_JSVAL(JS_NewStringCopyZ(cx,(char *)JS_GetImplementationVersion()));
        break;
    case PROP_TERMINATED:
        if(branch->terminated==NULL)
            *vp=JSVAL_FALSE;
        else
            *vp=BOOLEAN_TO_JSVAL(*branch->terminated);
        break;
    case PROP_AUTO_TERMINATE:
        *vp=BOOLEAN_TO_JSVAL(branch->auto_terminate);
        break;
    case PROP_BRANCH_COUNTER:
        JS_NewNumberValue(cx,branch->counter,vp);
        break;
    case PROP_BRANCH_LIMIT:
        JS_NewNumberValue(cx,branch->limit,vp);
        break;
    case PROP_YIELD_INTERVAL:
        JS_NewNumberValue(cx,branch->yield_interval,vp);
        break;
    case PROP_GC_INTERVAL:
        JS_NewNumberValue(cx,branch->gc_interval,vp);
        break;
    case PROP_GC_ATTEMPTS:
        JS_NewNumberValue(cx,branch->gc_attempts,vp);
        break;
#ifdef jscntxt_h___
    case PROP_GC_COUNTER:
        JS_NewNumberValue(cx,cx->runtime->gcNumber,vp);
        break;
    case PROP_GC_LASTBYTES:
        JS_NewNumberValue(cx,cx->runtime->gcLastBytes,vp);
        break;
    case PROP_BYTES:
        JS_NewNumberValue(cx,cx->runtime->gcBytes,vp);
        break;
    case PROP_MAXBYTES:
        JS_NewNumberValue(cx,cx->runtime->gcMaxBytes,vp);
        break;
    case PROP_GLOBAL:
        *vp = OBJECT_TO_JSVAL(cx->globalObject);
        break;
#else
    case PROP_GLOBAL:
        *vp = OBJECT_TO_JSVAL(JS_GetParent(cx,obj));
        break;
#endif
    }

    return(JS_TRUE);
}
JSBool XPCDispConvert::COMToJS(XPCCallContext& ccx, const VARIANT& src,
                               jsval& dest, nsresult& err)
{
    err = NS_OK;
    if(src.vt & VT_ARRAY || src.vt == VT_SAFEARRAY)
    {
        return COMArrayToJSArray(ccx, src, dest, err);
    }
    PRBool isPtr = src.vt & VT_BYREF;
    switch (src.vt & ~(VT_BYREF))
    {
        case VT_UINT:
        {
            return JS_NewNumberValue(ccx, VALUE(uintVal), &dest);
        }
        break;
        case VT_UI4:
        {
            return JS_NewNumberValue(ccx, VALUE(ulVal), &dest);
        }
        break;
        case VT_INT:
        {
            return JS_NewNumberValue(ccx, VALUE(intVal), &dest);
        }
        break;
        case VT_I4:
        {
            return JS_NewNumberValue(ccx, VALUE(lVal), &dest);
        }
        break;
        case VT_UI1:
        {
            dest = INT_TO_JSVAL(VALUE(bVal));
        }
        break;
        case VT_I1:
        {
            dest = INT_TO_JSVAL(VALUE(cVal));
        }
        break;
        case VT_UI2:
        {
            dest = INT_TO_JSVAL(VALUE(uiVal));
        }
        break;
        case VT_I2:
        {
            dest = INT_TO_JSVAL(VALUE(iVal));
        }
        break;
        case VT_R4:
        {
            return JS_NewNumberValue(ccx, VALUE(fltVal), &dest);
        }
        break;
        case VT_R8:
        {
            return JS_NewNumberValue(ccx, VALUE(dblVal), &dest);
        }
        break;
        case VT_BOOL:
        {
            dest = BOOLEAN_TO_JSVAL(VALUE(boolVal) != VARIANT_FALSE ? JS_TRUE : JS_FALSE);
        }
        break;
        case VT_DISPATCH:
        {
            XPCDispObject::WrapIDispatch(VALUE(pdispVal), ccx,
                                         JS_GetGlobalObject(ccx), &dest);
        }
        break;
        case VT_DATE:
        {
            // Convert date to string and frees it when we're done
            _bstr_t str(src);
            dest = StringToJSVal(ccx, str, str.length());
        }
        break;
        case VT_EMPTY:
        {
            dest = JSVAL_VOID;
        }
        break;
        case VT_NULL:
        {
            dest = JSVAL_NULL;
        }
        break;
        case VT_ERROR:
        {
            return JS_NewNumberValue(ccx, VALUE(scode), &dest);
        }
        break;
        case VT_CY:
        {
            return JS_NewNumberValue(
                ccx, 
                static_cast<double>
                           (isPtr ? src.pcyVal->int64 : 
                                       src.cyVal.int64) / 100.0,
                &dest);
        }
        break;
        /**
         * Currently unsupported conversion types
         */
        case VT_UNKNOWN:
        default:
        {
            // Last ditch effort to convert to string
            if(FAILED(VariantChangeType(const_cast<VARIANT*>(&src), 
                                         const_cast<VARIANT*>(&src), 
                                         VARIANT_ALPHABOOL, VT_BSTR)))
            {
                err = NS_ERROR_XPC_BAD_CONVERT_JS;
                return JS_FALSE;
            }
            isPtr = FALSE;
        } // Fall through on success
        case VT_BSTR:
        {
            dest = StringToJSVal(ccx, VALUE(bstrVal), SysStringLen(VALUE(bstrVal)));
        }
        break;
    }
    return JS_TRUE;
}
Пример #9
0
static JSBool js_user_get(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
	jsval idval;
	char*		s=NULL;
	char		tmp[128];
	uint64_t	val=0;
    jsint       tiny;
	JSString*	js_str;
	private_t*	p;
	jsrefcount	rc;
	scfg_t*			scfg;

	scfg=JS_GetRuntimePrivate(JS_GetRuntime(cx));

	if((p=(private_t*)JS_GetPrivate(cx,obj))==NULL)
		return(JS_TRUE);

	rc=JS_SUSPENDREQUEST(cx);
	js_getuserdat(scfg,p);

    JS_IdToValue(cx, id, &idval);
    tiny = JSVAL_TO_INT(idval);

	switch(tiny) {
		case USER_PROP_NUMBER:
			val=p->user->number;
			break;
		case USER_PROP_ALIAS: 
			s=p->user->alias;
			break;
		case USER_PROP_NAME:
			s=p->user->name;
			break;
		case USER_PROP_HANDLE:
			s=p->user->handle;
			break;
		case USER_PROP_NOTE:
			s=p->user->note;
			break;
		case USER_PROP_COMP:
			s=p->user->comp;
			break;
		case USER_PROP_COMMENT:
			s=p->user->comment;
			break;
		case USER_PROP_NETMAIL:
			s=p->user->netmail;
			break;
		case USER_PROP_EMAIL:
			s=usermailaddr(scfg, tmp
				,scfg->inetmail_misc&NMAIL_ALIAS ? p->user->alias : p->user->name);
			break;
		case USER_PROP_ADDRESS:
			s=p->user->address;
			break;
		case USER_PROP_LOCATION:
			s=p->user->location;
			break;
		case USER_PROP_ZIPCODE:
			s=p->user->zipcode;
			break;
		case USER_PROP_PASS:
			s=p->user->pass;
			break;
		case USER_PROP_PHONE:
			s=p->user->phone;
			break;
		case USER_PROP_BIRTH:
			s=p->user->birth;
			break;
		case USER_PROP_AGE:
			val=getage(scfg,p->user->birth);
			break;
		case USER_PROP_MODEM:
			s=p->user->modem;
			break;
		case USER_PROP_LASTON:
			val=p->user->laston;
			break;
		case USER_PROP_FIRSTON:
			val=p->user->firston;
			break;
		case USER_PROP_EXPIRE:
			val=p->user->expire;
			break;
		case USER_PROP_PWMOD: 
			val=p->user->pwmod;
			break;
		case USER_PROP_LOGONS:
			val=p->user->logons;
			break;
		case USER_PROP_LTODAY:
			val=p->user->ltoday;
			break;
		case USER_PROP_TIMEON:
			val=p->user->timeon;
			break;
		case USER_PROP_TEXTRA:
			val=p->user->textra;
			break;
		case USER_PROP_TTODAY:
			val=p->user->ttoday;
			break;
		case USER_PROP_TLAST: 
			val=p->user->tlast;
			break;
		case USER_PROP_POSTS: 
			val=p->user->posts;
			break;
		case USER_PROP_EMAILS: 
			val=p->user->emails;
			break;
		case USER_PROP_FBACKS: 
			val=p->user->fbacks;
			break;
		case USER_PROP_ETODAY:	
			val=p->user->etoday;
			break;
		case USER_PROP_PTODAY:
			val=p->user->ptoday;
			break;
		case USER_PROP_ULB:
			val=p->user->ulb;
			break;
		case USER_PROP_ULS:
			val=p->user->uls;
			break;
		case USER_PROP_DLB:
			val=p->user->dlb;
			break;
		case USER_PROP_DLS:
			val=p->user->dls;
			break;
		case USER_PROP_CDT:
			val=p->user->cdt;
			break;
		case USER_PROP_MIN:
			val=p->user->min;
			break;
		case USER_PROP_LEVEL:
			val=p->user->level;
			break;
		case USER_PROP_FLAGS1:
			val=p->user->flags1;
			break;
		case USER_PROP_FLAGS2:
			val=p->user->flags2;
			break;
		case USER_PROP_FLAGS3:
			val=p->user->flags3;
			break;
		case USER_PROP_FLAGS4:
			val=p->user->flags4;
			break;
		case USER_PROP_EXEMPT:
			val=p->user->exempt;
			break;
		case USER_PROP_REST:
			val=p->user->rest;
			break;
		case USER_PROP_ROWS:
			val=p->user->rows;
			break;
		case USER_PROP_SEX:
			sprintf(tmp,"%c",p->user->sex);
			s=tmp;
			break;
		case USER_PROP_MISC:
			val=p->user->misc;
			break;
		case USER_PROP_LEECH:
			val=p->user->leech;
			break;
		case USER_PROP_CURSUB:
			s=p->user->cursub;
			break;
		case USER_PROP_CURDIR:
			s=p->user->curdir;
			break;
		case USER_PROP_CURXTRN:
			s=p->user->curxtrn;
			break;

		case USER_PROP_FREECDT:
			val=p->user->freecdt;
			break;
		case USER_PROP_XEDIT:
			if(p->user->xedit>0 && p->user->xedit<=scfg->total_xedits)
				s=scfg->xedit[p->user->xedit-1]->code;
			else
				s=""; /* internal editor */
			break;
		case USER_PROP_SHELL:
			s=scfg->shell[p->user->shell]->code;
			break;
		case USER_PROP_QWK:
			val=p->user->qwk;
			break;
		case USER_PROP_TMPEXT:
			s=p->user->tmpext;
			break;
		case USER_PROP_CHAT:
			val=p->user->chat;
			break;
		case USER_PROP_NS_TIME:
			val=p->user->ns_time;
			break;
		case USER_PROP_PROT:
			sprintf(tmp,"%c",p->user->prot);
			s=tmp;
			break;
		case USER_PROP_LOGONTIME:
			val=p->user->logontime;
			break;
		case USER_PROP_TIMEPERCALL:
			val=scfg->level_timepercall[p->user->level];
			break;
		case USER_PROP_TIMEPERDAY:
			val=scfg->level_timeperday[p->user->level];
			break;
		case USER_PROP_CALLSPERDAY:
			val=scfg->level_callsperday[p->user->level];
			break;
		case USER_PROP_LINESPERMSG:
			val=scfg->level_linespermsg[p->user->level];
			break;
		case USER_PROP_POSTSPERDAY:
			val=scfg->level_postsperday[p->user->level];
			break;
		case USER_PROP_EMAILPERDAY:
			val=scfg->level_emailperday[p->user->level];
			break;
		case USER_PROP_FREECDTPERDAY:
			val=scfg->level_freecdtperday[p->user->level];
			break;
		case USER_PROP_MAIL_WAITING:
			val=getmail(scfg,p->user->number,/* sent? */FALSE);
			break;
		case USER_PROP_MAIL_PENDING:
			val=getmail(scfg,p->user->number,/* sent? */TRUE);
			break;

		case USER_PROP_CACHED:
			*vp = BOOLEAN_TO_JSVAL(p->cached);
			JS_RESUMEREQUEST(cx, rc);
			return(JS_TRUE);	/* intentional early return */

		case USER_PROP_IS_SYSOP:
			*vp = BOOLEAN_TO_JSVAL(p->user->level >= SYSOP_LEVEL);
			JS_RESUMEREQUEST(cx, rc);
			return(JS_TRUE);	/* intentional early return */

		default:	
			/* This must not set vp in order for child objects to work (stats and security) */
			JS_RESUMEREQUEST(cx, rc);
			return(JS_TRUE);
	}
	JS_RESUMEREQUEST(cx, rc);
	if(s!=NULL) {
		if((js_str=JS_NewStringCopyZ(cx, s))==NULL)
			return(JS_FALSE);
		*vp = STRING_TO_JSVAL(js_str);
	} else
		*vp=DOUBLE_TO_JSVAL((double)val);

	return(JS_TRUE);
}
Пример #10
0
js_ValueToIterator(JSContext *cx, uintN flags, jsval *vp)
{
    JSObject *obj;
    JSTempValueRooter tvr;
    JSAtom *atom;
    JSClass *clasp;
    JSExtendedClass *xclasp;
    JSBool ok;
    JSObject *iterobj;
    jsval arg;

    JS_ASSERT(!(flags & ~(JSITER_ENUMERATE |
                          JSITER_FOREACH |
                          JSITER_KEYVALUE)));

    /* JSITER_KEYVALUE must always come with JSITER_FOREACH */
    JS_ASSERT(!(flags & JSITER_KEYVALUE) || (flags & JSITER_FOREACH));

    /* XXX work around old valueOf call hidden beneath js_ValueToObject */
    if (!JSVAL_IS_PRIMITIVE(*vp)) {
        obj = JSVAL_TO_OBJECT(*vp);
    } else {
        /*
         * Enumerating over null and undefined gives an empty enumerator.
         * This is contrary to ECMA-262 9.9 ToObject, invoked from step 3 of
         * the first production in 12.6.4 and step 4 of the second production,
         * but it's "web JS" compatible.
         */
        if ((flags & JSITER_ENUMERATE)) {
            if (!js_ValueToObject(cx, *vp, &obj))
                return JS_FALSE;
            if (!obj)
                goto default_iter;
        } else {
            obj = js_ValueToNonNullObject(cx, *vp);
            if (!obj)
                return JS_FALSE;
        }
    }

    JS_ASSERT(obj);
    JS_PUSH_TEMP_ROOT_OBJECT(cx, obj, &tvr);

    clasp = OBJ_GET_CLASS(cx, obj);
    if ((clasp->flags & JSCLASS_IS_EXTENDED) &&
        (xclasp = (JSExtendedClass *) clasp)->iteratorObject) {
        iterobj = xclasp->iteratorObject(cx, obj, !(flags & JSITER_FOREACH));
        if (!iterobj)
            goto bad;
        *vp = OBJECT_TO_JSVAL(iterobj);
    } else {
        atom = cx->runtime->atomState.iteratorAtom;
#if JS_HAS_XML_SUPPORT
        if (OBJECT_IS_XML(cx, obj)) {
            if (!js_GetXMLFunction(cx, obj, ATOM_TO_JSID(atom), vp))
                goto bad;
        } else
#endif
        {
            if (!OBJ_GET_PROPERTY(cx, obj, ATOM_TO_JSID(atom), vp))
                goto bad;
        }

        if (JSVAL_IS_VOID(*vp)) {
          default_iter:
            /*
             * Fail over to the default enumerating native iterator.
             *
             * Create iterobj with a NULL parent to ensure that we use the
             * correct scope chain to lookup the iterator's constructor. Since
             * we use the parent slot to keep track of the iterable, we must
             * fix it up after.
             */
            iterobj = js_NewObject(cx, &js_IteratorClass, NULL, NULL, 0);
            if (!iterobj)
                goto bad;

            /* Store in *vp to protect it from GC (callers must root vp). */
            *vp = OBJECT_TO_JSVAL(iterobj);

            if (!InitNativeIterator(cx, iterobj, obj, flags))
                goto bad;
        } else {
            arg = BOOLEAN_TO_JSVAL((flags & JSITER_FOREACH) == 0);
            if (!js_InternalInvoke(cx, obj, *vp, JSINVOKE_ITERATOR, 1, &arg,
                                   vp)) {
                goto bad;
            }
            if (JSVAL_IS_PRIMITIVE(*vp)) {
                const char *printable = js_AtomToPrintableString(cx, atom);
                if (printable) {
                    js_ReportValueError2(cx, JSMSG_BAD_ITERATOR_RETURN,
                                         JSDVG_SEARCH_STACK, *vp, NULL,
                                         printable);
                }
                goto bad;
            }
        }
    }

    ok = JS_TRUE;
  out:
    if (obj)
        JS_POP_TEMP_ROOT(cx, &tvr);
    return ok;
  bad:
    ok = JS_FALSE;
    goto out;
}
Пример #11
0
static void 
add_bool(void *opaque, void *parent, const char *name, int v)
{
  js_set_prop_jsval(opaque, parent, name, BOOLEAN_TO_JSVAL(!!v));
}
Пример #12
0
DWORD FillBaseStat(JSContext* cx, jsval *argv, INT table, INT row, INT column, char* szTable, char* szStat)
{
	if(szTable)
	{
		table = -1;
		for(int i = 0; BaseStatTable[i].pTable != NULL; i++)
			if(!_strcmpi(szTable, BaseStatTable[i].szTableName))
			{
				table = i;
				break;
			}

		if(table == -1)
			return false;
	}

	BinField* pTable = BaseStatTable[table].pTable;

	if(szStat)
	{
		column = -1;
		for(int i = 0; i < BaseStatTable[table].wTableSize; i++)
			if(!_strcmpi(szStat, pTable[i].szFieldName))
			{
				column = i;
				break;
			}

		if(column == -1)
			return false;
	}

	if(column > BaseStatTable[table].wTableSize)
		return FALSE;

	DWORD dwBuffer = 0;
	WORD wBuffer = 0;
	char* szBuffer = NULL;
	DWORD dwHelperSize = pTable[column+1].dwFieldOffset - pTable[column].dwFieldOffset;
	if(dwHelperSize > 4)
		dwHelperSize = 4;

	switch(pTable[column].eFieldType)
	{
		case FIELDTYPE_DATA_ASCII:
			szBuffer = new char[(pTable[column].dwFieldLength + 1)];
			memset(szBuffer, NULL, pTable[column].dwFieldLength + 1);
			if(!FillBaseStat(table, row, column, szBuffer, pTable[column].dwFieldLength+1))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szBuffer));
			delete[] szBuffer;
			return TRUE;

		case FIELDTYPE_DATA_DWORD:
		case FIELDTYPE_CALC_TO_DWORD:
		case FIELDTYPE_NAME_TO_DWORD:
		case FIELDTYPE_DATA_DWORD_2:
		case FIELDTYPE_UNKNOWN_11:
			if(!FillBaseStat(table, row, column, &dwBuffer, sizeof(DWORD)))
				(*argv) = JSVAL_VOID;
			else
				JS_NewNumberValue(cx, (jsdouble)dwBuffer, argv);
			return TRUE;

		case FIELDTYPE_NAME_TO_INDEX_2:
		case FIELDTYPE_NAME_TO_WORD_2:
		case FIELDTYPE_NAME_TO_INDEX:
		case FIELDTYPE_NAME_TO_WORD:
		case FIELDTYPE_KEY_TO_WORD:
		case FIELDTYPE_DATA_WORD:
		case FIELDTYPE_CODE_TO_WORD:
			if(!FillBaseStat(table, row, column, &wBuffer, sizeof(WORD)))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = INT_TO_JSVAL(wBuffer);
			return TRUE;

		case FIELDTYPE_CODE_TO_BYTE:
		case FIELDTYPE_DATA_BYTE_2:
		case FIELDTYPE_DATA_BYTE:
			if(!FillBaseStat(table, row, column, &dwBuffer, dwHelperSize))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = INT_TO_JSVAL(dwBuffer);
			return TRUE;

		case FIELDTYPE_DATA_BIT:
			if(!FillBaseStat(table, row, column, &dwBuffer, sizeof(DWORD)))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = BOOLEAN_TO_JSVAL(!!dwBuffer);
			return TRUE;

		case FIELDTYPE_ASCII_TO_CODE:
		case FIELDTYPE_DATA_RAW:
			szBuffer = new char[5];
			memset(szBuffer, NULL, 5);
			if(!FillBaseStat(table, row, column, szBuffer, 5))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szBuffer));
			delete[] szBuffer;
			return TRUE;

		case FIELDTYPE_MONSTER_COMPS:
			// ..? :E
			return FALSE;
	}
	return FALSE;
}
//
// Native method StartSoftwareUpdate
//
static JSBool
InstallTriggerGlobalStartSoftwareUpdate(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  nsIDOMInstallTriggerGlobal *nativeThis = getTriggerNative(cx, obj);
  if (!nativeThis)
    return JS_FALSE;

  PRBool       nativeRet;
  PRInt32      flags = 0;

  *rval = JSVAL_FALSE;

  nsIScriptGlobalObject *globalObject = nsnull;
  nsIScriptContext *scriptContext = GetScriptContextFromJSContext(cx);
  if (scriptContext)
      globalObject = scriptContext->GetGlobalObject();

  if (!globalObject)
      return JS_TRUE;

  // get window.location to construct relative URLs
  nsCOMPtr<nsIURI> baseURL;
  JSObject* global = JS_GetGlobalObject(cx);
  if (global)
  {
    jsval v;
    if (JS_GetProperty(cx,global,"location",&v))
    {
      nsAutoString location;
      ConvertJSValToStr( location, cx, v );
      NS_NewURI(getter_AddRefs(baseURL), location);
    }
  }


  if ( argc >= 1 )
  {
    nsAutoString xpiURL;
    ConvertJSValToStr(xpiURL, cx, argv[0]);
    if (baseURL)
    {
        nsCAutoString resolvedURL;
        baseURL->Resolve(NS_ConvertUTF16toUTF8(xpiURL), resolvedURL);
        xpiURL = NS_ConvertUTF8toUTF16(resolvedURL);
    }

    // Make sure caller is allowed to load this url.
    nsresult rv = InstallTriggerCheckLoadURIFromScript(cx, xpiURL);
    if (NS_FAILED(rv))
        return JS_FALSE;

    if (argc >= 2 && !JS_ValueToInt32(cx, argv[1], (int32 *)&flags))
    {
        JS_ReportError(cx, "StartSoftwareUpdate() 2nd parameter must be a number");
        return JS_FALSE;
    }

    nsCOMPtr<nsIURI> checkuri;
    rv = nativeThis->GetOriginatingURI(globalObject, getter_AddRefs(checkuri));
    if (NS_SUCCEEDED(rv))
    {
        nsAutoPtr<nsXPITriggerInfo> trigger(new nsXPITriggerInfo());
        nsAutoPtr<nsXPITriggerItem> item(new nsXPITriggerItem(0,
                                                              xpiURL.get(),
                                                              nsnull));
        if (trigger && item)
        {
            // trigger will free item when complete
            trigger->Add(item.forget());
            nsCOMPtr<nsIDOMWindowInternal> win(do_QueryInterface(globalObject));
            nsCOMPtr<nsIXPIInstallInfo> installInfo =
                                new nsXPIInstallInfo(win, checkuri, trigger, 0);
            if (installInfo)
            {
                // From here trigger is owned by installInfo until passed on to nsXPInstallManager
                trigger.forget();
                PRBool enabled = PR_FALSE;
                nativeThis->UpdateEnabled(checkuri, XPI_WHITELIST, &enabled);
                if (!enabled)
                {
                    nsCOMPtr<nsIObserverService> os =
                      mozilla::services::GetObserverService();
                    if (os)
                        os->NotifyObservers(installInfo,
                                            "xpinstall-install-blocked",
                                            nsnull);
                }
                else
                {
                    nativeThis->StartInstall(installInfo, &nativeRet);
                    *rval = BOOLEAN_TO_JSVAL(nativeRet);
                }
            }
        }
    }
  }
  else
  {
    JS_ReportError(cx, "Function StartSoftwareUpdate requires 1 parameters");
    return JS_FALSE;
  }

  return JS_TRUE;
}
Пример #14
0
void jsb_register_cocos2d_config( JSContext *_cx, JSObject *cocos2d)
{
    // Config Object
    JSObject *ccconfig = JS_NewObject(_cx, NULL, NULL, NULL);
    // config.os: The Operating system
    // osx, ios, android, windows, linux, etc..
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    JSString *str = JS_InternString(_cx, "ios");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JSString *str = JS_InternString(_cx, "android");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    JSString *str = JS_InternString(_cx, "windows");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
    JSString *str = JS_InternString(_cx, "marmalade");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
    JSString *str = JS_InternString(_cx, "linux");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)
    JSString *str = JS_InternString(_cx, "bada");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
    JSString *str = JS_InternString(_cx, "blackberry");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
    JSString *str = JS_InternString(_cx, "osx");
#else
    JSString *str = JS_InternString(_cx, "unknown");
#endif
    JS_DefineProperty(_cx, ccconfig, "os", STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    // config.deviceType: Device Type
    // 'mobile' for any kind of mobile devices, 'desktop' for PCs, 'browser' for Web Browsers
// #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
//     str = JS_InternString(_cx, "desktop");
// #else
    str = JS_InternString(_cx, "mobile");
// #endif
    JS_DefineProperty(_cx, ccconfig, "platform", STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    // config.engine: Type of renderer
    // 'cocos2d', 'cocos2d-x', 'cocos2d-html5/canvas', 'cocos2d-html5/webgl', etc..
    str = JS_InternString(_cx, "cocos2d-x");
    JS_DefineProperty(_cx, ccconfig, "engine", STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    // config.arch: CPU Architecture
    // i386, ARM, x86_64, web
#ifdef __LP64__
    str = JS_InternString(_cx, "x86_64");
#elif defined(__arm__) || defined(__ARM_NEON__)
    str = JS_InternString(_cx, "arm");
#else
    str = JS_InternString(_cx, "i386");
#endif
    JS_DefineProperty(_cx, ccconfig, "arch", STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    // config.version: Version of cocos2d + renderer
    str = JS_InternString(_cx, cocos2dVersion() );
    JS_DefineProperty(_cx, ccconfig, "version", STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    // config.usesTypedArrays
#if JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES
    JSBool b = JS_FALSE;
#else
    JSBool b = JS_TRUE;
#endif
    JS_DefineProperty(_cx, ccconfig, "usesTypedArrays", BOOLEAN_TO_JSVAL(b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    // config.debug: Debug build ?
#if COCOS2D_DEBUG > 0
    b = JS_TRUE;
#else
    b = JS_FALSE;
#endif
    JS_DefineProperty(_cx, ccconfig, "debug", BOOLEAN_TO_JSVAL(b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);


    // Add "config" to "cc"
    JS_DefineProperty(_cx, cocos2d, "config", OBJECT_TO_JSVAL(ccconfig), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
}
Пример #15
0
jsval CStdDeserializer::ReadScriptVal(JSObject* appendParent)
{
	JSContext* cx = m_ScriptInterface.GetContext();

	uint8_t type;
	NumberU8_Unbounded("type", type);
	switch (type)
	{
	case SCRIPT_TYPE_VOID:
		return JSVAL_VOID;

	case SCRIPT_TYPE_NULL:
		return JSVAL_NULL;

	case SCRIPT_TYPE_ARRAY:
	case SCRIPT_TYPE_OBJECT:
	{
		JSObject* obj;
		if (appendParent)
			obj = appendParent;
		else if (type == SCRIPT_TYPE_ARRAY)
			obj = JS_NewArrayObject(cx, 0, NULL);
		else
			obj = JS_NewObject(cx, NULL, NULL, NULL);

		if (!obj)
			throw PSERROR_Deserialize_ScriptError();
		CScriptValRooted objRoot(cx, OBJECT_TO_JSVAL(obj));

		AddScriptBackref(obj);

		uint32_t numProps;
		NumberU32_Unbounded("num props", numProps);

		for (uint32_t i = 0; i < numProps; ++i)
		{
			utf16string propname;
			ReadStringUTF16(propname);

			jsval propval = ReadScriptVal(NULL);
			CScriptValRooted propvalRoot(cx, propval);

			if (!JS_SetUCProperty(cx, obj, (const jschar*)propname.data(), propname.length(), &propval))
				throw PSERROR_Deserialize_ScriptError();
		}

		return OBJECT_TO_JSVAL(obj);
	}
	case SCRIPT_TYPE_STRING:
	{
		JSString* str;
		ScriptString("string", str);
		return STRING_TO_JSVAL(str);
	}
	case SCRIPT_TYPE_INT:
	{
		int32_t value;
		NumberI32("value", value, JSVAL_INT_MIN, JSVAL_INT_MAX);
		return INT_TO_JSVAL(value);
	}
	case SCRIPT_TYPE_DOUBLE:
	{
		double value;
		NumberDouble_Unbounded("value", value);
		jsval rval;
		if (!JS_NewNumberValue(cx, value, &rval))
			throw PSERROR_Deserialize_ScriptError("JS_NewNumberValue failed");
		return rval;
	}
	case SCRIPT_TYPE_BOOLEAN:
	{
		uint8_t value;
		NumberU8("value", value, 0, 1);
		return BOOLEAN_TO_JSVAL(value ? JS_TRUE : JS_FALSE);
	}
	case SCRIPT_TYPE_BACKREF:
	{
		u32 tag;
		NumberU32_Unbounded("tag", tag);
		JSObject* obj = GetScriptBackref(tag);
		if (!obj)
			throw PSERROR_Deserialize_ScriptError("Invalid backref tag");
		return OBJECT_TO_JSVAL(obj);
	}
	default:
		throw PSERROR_Deserialize_OutOfBounds();
	}
}
Пример #16
0
LRESULT WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

	CxObj *cxobj = (CxObj*)GetWindowLong(hWnd, GWL_USERDATA);
	if ( cxobj == NULL )
		return DefWindowProc(hWnd, message, wParam, lParam);

	JSContext *cx = cxobj->cx;
	JS::RootedObject obj(cx, cxobj->obj);

	jsval rval;
	jsval functionVal;

	LRESULT returnValue = 0;

	switch (message) {

		//case WM_COMMAND:
		//case WM_PAINT

		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
		case WM_CHAR:
			JS_GetProperty(cx, obj, "onchar", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				char c = wParam;
				jsval argv[] = { STRING_TO_JSVAL(JS_NewStringCopyN(cx, &c, 1)), INT_TO_JSVAL(lParam) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // needed to protect the new string
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_KEYUP:
			JS_GetProperty(cx, obj, "onkeyup", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { INT_TO_JSVAL(wParam), INT_TO_JSVAL(lParam) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_KEYDOWN:
			JS_GetProperty(cx, obj, "onkeydown", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { INT_TO_JSVAL(wParam), INT_TO_JSVAL(lParam) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_ACTIVATE:
			JS_GetProperty(cx, obj, "onactivate", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { BOOLEAN_TO_JSVAL(wParam != WA_INACTIVE) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
//		case WM_SIZING:
		case WM_SIZE:
			JS_GetProperty(cx, obj, "onsize", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { INT_TO_JSVAL((short)LOWORD(lParam)), INT_TO_JSVAL((short)HIWORD(lParam)) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_MOUSEMOVE:
			JS_GetProperty(cx, obj, "onmousemove", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { INT_TO_JSVAL(MAKEPOINTS(lParam).x), INT_TO_JSVAL(MAKEPOINTS(lParam).y), BOOLEAN_TO_JSVAL(wParam & MK_LBUTTON), BOOLEAN_TO_JSVAL(wParam & MK_RBUTTON), BOOLEAN_TO_JSVAL(wParam & MK_MBUTTON) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_MOUSEWHEEL:
			JS_GetProperty(cx, obj, "onmousewheel", &functionVal);
			if ( !functionVal.isUndefined() ) {

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { INT_TO_JSVAL( GET_WHEEL_DELTA_WPARAM(wParam)/WHEEL_DELTA ), BOOLEAN_TO_JSVAL(wParam & MK_LBUTTON), BOOLEAN_TO_JSVAL(wParam & MK_RBUTTON), BOOLEAN_TO_JSVAL(wParam & MK_MBUTTON) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_LBUTTONDOWN:
		case WM_MBUTTONDOWN:
		case WM_RBUTTONDOWN:
			JS_GetProperty(cx, obj, "onmousedown", &functionVal);
			if ( !functionVal.isUndefined() ) {

				// xPos = GET_X_LPARAM(lParam);
				// yPos = GET_Y_LPARAM(lParam);

				JL_ASSERT_FUNCTION(functionVal); // (TBD) return value of assert is not compatible with this function (WndProc)
				jsval argv[] = { INT_TO_JSVAL( message==WM_LBUTTONDOWN ? 1 : message==WM_RBUTTONDOWN ? 2 : message==WM_MBUTTONDOWN ? 3 : 0 ), JSVAL_TRUE };
//					BOOLEAN_TO_JSVAL(wParam & MK_LBUTTON),
//					BOOLEAN_TO_JSVAL(wParam & MK_RBUTTON),
//					BOOLEAN_TO_JSVAL(wParam & MK_MBUTTON) };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;
		case WM_LBUTTONUP:
		case WM_MBUTTONUP:
		case WM_RBUTTONUP:
			JS_GetProperty(cx, obj, "onmouseup", &functionVal);
			if ( !functionVal.isUndefined() ) {

				// xPos = GET_X_LPARAM(lParam);
				// yPos = GET_Y_LPARAM(lParam);

				JL_ASSERT( JS_TypeOfValue( cx, functionVal ) == JSTYPE_FUNCTION, "Need a function." );
				jsval argv[] = { INT_TO_JSVAL( message==WM_LBUTTONUP ? 1 : message==WM_RBUTTONUP ? 2 : message==WM_MBUTTONUP ? 3 : 0 ), JSVAL_FALSE };
				JSTempValueRooter tvr;
				JS_PUSH_TEMP_ROOT(cx, COUNTOF(argv), argv, &tvr); // not really needed
				bool status = JS_CallFunctionValue(cx, obj, functionVal, COUNTOF(argv), argv, &rval);
				JS_POP_TEMP_ROOT(cx, &tvr);
				JL_CHK( status );
				return 0;
			}
			break;

		//case WM_MOUSELEAVE: // need TrackMouseEvent() ...
		//	JS_GetProperty(cx, obj, "onmouseleave", &functionVal);
		//	if ( !JSVAL_IS_VOID( functionVal ) ) {

		//		JS_CallFunctionValue(cx, obj, functionVal, 0, NULL, &rval);
		//	}
		//	break;
	}
	return DefWindowProc(hWnd, message, wParam, lParam); // We do not want to handle this message so pass back to Windows to handle it in a default way
}
bool js_cocos2dx_extension_EventListenerAssetsManagerEx_init(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
    js_proxy_t *proxy = jsb_get_js_proxy(obj);
    cocos2d::extension::EventListenerAssetsManagerEx* cobj = (cocos2d::extension::EventListenerAssetsManagerEx *)(proxy ? proxy->ptr : NULL);
    JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_extension_EventListenerAssetsManagerEx_init : Invalid Native Object");
    if (argc == 2) {
        const cocos2d::extension::AssetsManagerEx* arg0 = nullptr;
        std::function<void (cocos2d::extension::EventAssetsManagerEx *)> arg1;
        do {
            if (args.get(0).isNull()) { arg0 = nullptr; break; }
            if (!args.get(0).isObject()) { ok = false; break; }
            js_proxy_t *jsProxy;
            JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull());
            jsProxy = jsb_get_js_proxy(tmpObj);
            arg0 = (const cocos2d::extension::AssetsManagerEx*)(jsProxy ? jsProxy->ptr : NULL);
            JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
        } while (0);
        do {
            if(JS_TypeOfValue(cx, args.get(1)) == JSTYPE_FUNCTION)
            {
                JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
                std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(1)));
                auto lambda = [=](cocos2d::extension::EventAssetsManagerEx* larg0) -> void {
                    JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
                    jsval largv[1];
                    do {
                        if (larg0) {
                            js_type_class_t* typeClass = js_get_type_from_native<cocos2d::extension::EventAssetsManagerEx>(larg0);
                            largv[0] = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(cx, larg0, typeClass, "cocos2d::extension::EventAssetsManagerEx"));
                        } else {
                            largv[0] = JSVAL_NULL;
                        }
                    } while (0);
                    JS::RootedValue rval(cx);
                    bool succeed = func->invoke(1, &largv[0], &rval);
                    if (!succeed && JS_IsExceptionPending(cx)) {
                        JS_ReportPendingException(cx);
                    }
                    removeJSObject(cx, larg0);
                };
                arg1 = lambda;
            }
            else
            {
                arg1 = nullptr;
            }
        } while(0)
            ;
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_extension_EventListenerAssetsManagerEx_init : Error processing arguments");
        bool ret = cobj->init(arg0, arg1);
        jsval jsret = JSVAL_NULL;
        jsret = BOOLEAN_TO_JSVAL(ret);
        args.rval().set(jsret);
        return true;
    }

    JS_ReportError(cx, "js_cocos2dx_extension_EventListenerAssetsManagerEx_init : wrong number of arguments: %d, was expecting %d", argc, 2);
    return false;
}
Пример #18
0
static JSBool
XDRValueBody(JSXDRState *xdr, uint32 type, jsval *vp)
{
    switch (type) {
      case JSVAL_XDRNULL:
        *vp = JSVAL_NULL;
        break;
      case JSVAL_XDRVOID:
        *vp = JSVAL_VOID;
        break;
      case JSVAL_STRING: {
        JSString *str;
        if (xdr->mode == JSXDR_ENCODE)
            str = JSVAL_TO_STRING(*vp);
        if (!JS_XDRString(xdr, &str))
            return JS_FALSE;
        if (xdr->mode == JSXDR_DECODE)
            *vp = STRING_TO_JSVAL(str);
        break;
      }
      case JSVAL_DOUBLE: {
        jsdouble *dp = (xdr->mode == JSXDR_ENCODE) ? JSVAL_TO_DOUBLE(*vp) : NULL;
        if (!JS_XDRDouble(xdr, &dp))
            return JS_FALSE;
        if (xdr->mode == JSXDR_DECODE)
            *vp = DOUBLE_TO_JSVAL(dp);
        break;
      }
      case JSVAL_OBJECT: {
        JSObject *obj;
        if (xdr->mode == JSXDR_ENCODE)
            obj = JSVAL_TO_OBJECT(*vp);
        if (!js_XDRObject(xdr, &obj))
            return JS_FALSE;
        if (xdr->mode == JSXDR_DECODE)
            *vp = OBJECT_TO_JSVAL(obj);
        break;
      }
      case JSVAL_SPECIAL: {
        uint32 b;
        if (xdr->mode == JSXDR_ENCODE)
            b = (uint32) JSVAL_TO_BOOLEAN(*vp);
        if (!JS_XDRUint32(xdr, &b))
            return JS_FALSE;
        if (xdr->mode == JSXDR_DECODE)
            *vp = BOOLEAN_TO_JSVAL(!!b);
        break;
      }
      default: {
        uint32 i;

        JS_ASSERT(type & JSVAL_INT);
        if (xdr->mode == JSXDR_ENCODE)
            i = (uint32) JSVAL_TO_INT(*vp);
        if (!JS_XDRUint32(xdr, &i))
            return JS_FALSE;
        if (xdr->mode == JSXDR_DECODE)
            *vp = INT_TO_JSVAL((int32) i);
        break;
      }
    }
    return JS_TRUE;
}
Пример #19
0
Файл: js.c Проект: Hr-/showtime
int
js_plugin_load(const char *id, const char *url, char *errbuf, size_t errlen)
{
  char *sbuf;
  struct fa_stat fs;
  JSContext *cx;
  js_plugin_t *jsp;
  JSObject *pobj, *gobj;
  JSScript *s;
  char path[PATH_MAX];
  jsval val;
  fa_handle_t *ref;
  
  ref = fa_reference(url);

  if((sbuf = fa_quickload(url, &fs, NULL, errbuf, errlen)) == NULL) {
    fa_unreference(ref);
    return -1;
  }

  cx = js_newctx(err_reporter);
  JS_BeginRequest(cx);

  /* Remove any plugin with same URL */
  LIST_FOREACH(jsp, &js_plugins, jsp_link)
    if(!strcmp(jsp->jsp_id, id))
      break;
  if(jsp != NULL)
    js_plugin_unload0(cx, jsp);

  jsp = calloc(1, sizeof(js_plugin_t));
  jsp->jsp_url = strdup(url);
  jsp->jsp_id  = strdup(id);
  jsp->jsp_ref = ref;
  
  LIST_INSERT_HEAD(&js_plugins, jsp, jsp_link);

  gobj = JS_NewObject(cx, &global_class, NULL, NULL);
  JS_InitStandardClasses(cx, gobj);

  JS_DefineProperty(cx, gobj, "showtime", OBJECT_TO_JSVAL(showtimeobj),
		    NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT);

  /* Plugin object */
  pobj = JS_NewObject(cx, &plugin_class, NULL, gobj);
  JS_AddNamedRoot(cx, &pobj, "plugin");

  JS_SetPrivate(cx, pobj, jsp);

  JS_DefineFunctions(cx, pobj, plugin_functions);


  val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, url));
  JS_SetProperty(cx, pobj, "url", &val);

  if(!fa_parent(path, sizeof(path), url)) {
    val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, path));
    JS_SetProperty(cx, pobj, "path", &val);
  }

  JS_DefineProperty(cx, pobj, "URIRouting", BOOLEAN_TO_JSVAL(1),
		    NULL, jsp_setEnableURIRoute, JSPROP_PERMANENT);
  jsp->jsp_enable_uri_routing = 1;

  JS_DefineProperty(cx, pobj, "search", BOOLEAN_TO_JSVAL(1),
		    NULL, jsp_setEnableSearch, JSPROP_PERMANENT);
  jsp->jsp_enable_search = 1;

  jsp->jsp_protect_object = 1;

  s = JS_CompileScript(cx, pobj, sbuf, fs.fs_size, url, 1);
  free(sbuf);

  if(s != NULL) {
    JSObject *sobj = JS_NewScriptObject(cx, s);
    jsval result;

    JS_AddNamedRoot(cx, &sobj, "script");
    JS_ExecuteScript(cx, pobj, s, &result);
    JS_RemoveRoot(cx, &sobj);
  }

  JS_RemoveRoot(cx, &pobj);
  JS_EndRequest(cx);
  JS_GC(cx);
  JS_DestroyContext(cx);
  return 0;
}
static bool js_is_native_obj(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp)
{
    vp.set(BOOLEAN_TO_JSVAL(true));
    return true;    
}
//
// Native method Install
//
static JSBool
InstallTriggerGlobalInstall(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  nsIDOMInstallTriggerGlobal *nativeThis = getTriggerNative(cx, obj);
  if (!nativeThis)
    return JS_FALSE;

  *rval = JSVAL_FALSE;

  // make sure XPInstall is enabled, return false if not
  nsIScriptGlobalObject *globalObject = nsnull;
  nsIScriptContext *scriptContext = GetScriptContextFromJSContext(cx);
  if (scriptContext)
    globalObject = scriptContext->GetGlobalObject();

  if (!globalObject)
      return JS_TRUE;

  nsCOMPtr<nsIScriptSecurityManager> secman(do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID));
  if (!secman)
  {
    JS_ReportError(cx, "Could not the script security manager service.");
    return JS_FALSE;
  }
  // get the principal.  if it doesn't exist, die.
  nsCOMPtr<nsIPrincipal> principal;
  secman->GetSubjectPrincipal(getter_AddRefs(principal));
  if (!principal)
  {
    JS_ReportError(cx, "Could not get the Subject Principal during InstallTrigger.Install()");
    return JS_FALSE;
  }

  // get window.location to construct relative URLs
  nsCOMPtr<nsIURI> baseURL;
  JSObject* global = JS_GetGlobalObject(cx);
  if (global)
  {
    jsval v;
    if (JS_GetProperty(cx,global,"location",&v))
    {
      nsAutoString location;
      ConvertJSValToStr( location, cx, v );
      NS_NewURI(getter_AddRefs(baseURL), location);
    }
  }

  PRBool abortLoad = PR_FALSE;

  // parse associative array of installs
  if ( argc >= 1 && JSVAL_IS_OBJECT(argv[0]) && JSVAL_TO_OBJECT(argv[0]) )
  {
    nsXPITriggerInfo *trigger = new nsXPITriggerInfo();
    if (!trigger)
      return JS_FALSE;

    trigger->SetPrincipal(principal);

    JSIdArray *ida = JS_Enumerate( cx, JSVAL_TO_OBJECT(argv[0]) );
    if ( ida )
    {
      jsval v;
      const PRUnichar *name, *URL;
      const PRUnichar *iconURL = nsnull;

      for (int i = 0; i < ida->length && !abortLoad; i++ )
      {
        JS_IdToValue( cx, ida->vector[i], &v );
        JSString * str = JS_ValueToString( cx, v );
        if (!str)
        {
          abortLoad = PR_TRUE;
          break;
        }

        name = reinterpret_cast<const PRUnichar*>(JS_GetStringChars( str ));

        URL = iconURL = nsnull;
        JSAutoByteString hash;
        JS_GetUCProperty( cx, JSVAL_TO_OBJECT(argv[0]), reinterpret_cast<const jschar*>(name), nsCRT::strlen(name), &v );
        if ( JSVAL_IS_OBJECT(v) && JSVAL_TO_OBJECT(v) )
        {
          jsval v2;
          if (JS_GetProperty( cx, JSVAL_TO_OBJECT(v), "URL", &v2 ) && !JSVAL_IS_VOID(v2)) {
            JSString *str = JS_ValueToString(cx, v2);
            if (!str) {
              abortLoad = PR_TRUE;
              break;
            }
            URL = reinterpret_cast<const PRUnichar*>(JS_GetStringChars(str));
          }

          if (JS_GetProperty( cx, JSVAL_TO_OBJECT(v), "IconURL", &v2 ) && !JSVAL_IS_VOID(v2)) {
            JSString *str = JS_ValueToString(cx, v2);
            if (!str) {
              abortLoad = PR_TRUE;
              break;
            }
            iconURL = reinterpret_cast<const PRUnichar*>(JS_GetStringChars(str));
          }

          if (JS_GetProperty( cx, JSVAL_TO_OBJECT(v), "Hash", &v2) && !JSVAL_IS_VOID(v2)) {
            JSString *str = JS_ValueToString(cx, v2);
            if (!str || !hash.encode(cx, str)) {
              abortLoad = PR_TRUE;
              break;
            }
          }
        }
        else
        {
          JSString *str = JS_ValueToString(cx, v);
          if (!str) {
            abortLoad = PR_TRUE;
            break;
          }
          URL = reinterpret_cast<const PRUnichar*>(JS_GetStringChars(str));
        }

        if ( URL )
        {
            // Get relative URL to load
            nsAutoString xpiURL(URL);
            if (baseURL)
            {
                nsCAutoString resolvedURL;
                baseURL->Resolve(NS_ConvertUTF16toUTF8(xpiURL), resolvedURL);
                xpiURL = NS_ConvertUTF8toUTF16(resolvedURL);
            }

            nsAutoString icon(iconURL);
            if (iconURL && baseURL)
            {
                nsCAutoString resolvedIcon;
                baseURL->Resolve(NS_ConvertUTF16toUTF8(icon), resolvedIcon);
                icon = NS_ConvertUTF8toUTF16(resolvedIcon);
            }

            // Make sure we're allowed to load this URL and the icon URL
            nsresult rv = InstallTriggerCheckLoadURIFromScript(cx, xpiURL);
            if (NS_FAILED(rv))
                abortLoad = PR_TRUE;

            if (!abortLoad && iconURL)
            {
                rv = InstallTriggerCheckLoadURIFromScript(cx, icon);
                if (NS_FAILED(rv))
                    abortLoad = PR_TRUE;
            }

            if (!abortLoad)
            {
                // Add the install item to the trigger collection
                nsXPITriggerItem *item =
                    new nsXPITriggerItem( name, xpiURL.get(), icon.get(), hash );
                if ( item )
                {
                    trigger->Add( item );
                }
                else
                    abortLoad = PR_TRUE;
            }
        }
        else
            abortLoad = PR_TRUE;
      }
      JS_DestroyIdArray( cx, ida );
    }


    // pass on only if good stuff found
    if (!abortLoad && trigger->Size() > 0)
    {
        nsCOMPtr<nsIURI> checkuri;
        nsresult rv = nativeThis->GetOriginatingURI(globalObject,
                                                    getter_AddRefs(checkuri));
        if (NS_SUCCEEDED(rv))
        {
            nsCOMPtr<nsIDOMWindowInternal> win(do_QueryInterface(globalObject));
            nsCOMPtr<nsIXPIInstallInfo> installInfo =
                new nsXPIInstallInfo(win, checkuri, trigger, 0);
            if (installInfo)
            {
                // installInfo now owns triggers
                PRBool enabled = PR_FALSE;
                nativeThis->UpdateEnabled(checkuri, XPI_WHITELIST, &enabled);
                if (!enabled)
                {
                    nsCOMPtr<nsIObserverService> os =
                      mozilla::services::GetObserverService();
                    if (os)
                        os->NotifyObservers(installInfo,
                                            "xpinstall-install-blocked",
                                            nsnull);
                }
                else
                {
                    // save callback function if any (ignore bad args for now)
                    if ( argc >= 2 && JS_TypeOfValue(cx,argv[1]) == JSTYPE_FUNCTION )
                    {
                        trigger->SaveCallback( cx, argv[1] );
                    }

                    PRBool result;
                    nativeThis->StartInstall(installInfo, &result);
                    *rval = BOOLEAN_TO_JSVAL(result);
                }
                return JS_TRUE;
            }
        }
    }
    // didn't pass it on so we must delete trigger
    delete trigger;
  }

  JS_ReportError(cx, "Incorrect arguments to InstallTrigger.Install()");
  return JS_FALSE;
}