示例#1
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_output_stream_write(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                             size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 2
        && JSValueGetType(ctx, args[0]) == kJSTypeString
        && JSValueGetType(ctx, args[1]) == kJSTypeObject) {

        char *descriptor = value_to_c_string(ctx, args[0]);

        unsigned int count = (unsigned int) array_get_count(ctx, (JSObjectRef) args[1]);
        uint8_t buf[count];
        for (unsigned int i = 0; i < count; i++) {
            JSValueRef v = array_get_value_at_index(ctx, (JSObjectRef) args[1], i);
            if (JSValueIsNumber(ctx, v)) {
                double n = JSValueToNumber(ctx, v, NULL);
                if (0 <= n && n <= 255) {
                    buf[i] = (uint8_t) n;
                } else {
                    fprintf(stderr, "Output stream value out of range %f", n);
                }
            } else {
                fprintf(stderr, "Output stream value not a number");
            }
        }

        file_write(descriptor_str_to_int(descriptor), count, buf);

        free(descriptor);
    }

    return JSValueMakeNull(ctx);
}
示例#2
0
const char* jsvalue_to_signature(JSContextRef ctx, JSValueRef jsvalue)
{
  switch (JSValueGetType(ctx, jsvalue))
  {
    case kJSTypeBoolean:
      {
          return DBUS_TYPE_BOOLEAN_AS_STRING;
      }
    case kJSTypeNumber:
      {
          return DBUS_TYPE_DOUBLE_AS_STRING;
      }
    case kJSTypeString:
      {
          return DBUS_TYPE_STRING_AS_STRING;
      }
    case kJSTypeObject:
      {
          return NULL;

        /*if (jsvalue_instanceof(ctx, jsvalue, "Array"))*/
        /*{*/
          /*char *array_signature;*/

          /*propnames = JSObjectCopyPropertyNames(ctx, (JSObjectRef)jsvalue);*/
          /*if (!jsarray_get_signature(ctx, jsvalue, propnames, &array_signature))*/
          /*{ */
            /*g_warning("Could not create array signature");*/
            /*JSPropertyNameArrayRelease(propnames);*/
            /*break;*/
          /*}*/
          /*signature = g_strdup_printf("a%s", array_signature);*/
          /*g_free(array_signature);*/
          /*JSPropertyNameArrayRelease(propnames);*/
          /*break;*/
        /*}*/

        /*[> Default conversion is to dict <]*/
        /*propnames = JSObjectCopyPropertyNames(ctx, (JSObjectRef)jsvalue);*/
        /*jsdict_get_signature(ctx, jsvalue, propnames, &dict_signature);*/
        /*if (dict_signature != NULL)*/
        /*{*/
          /*signature = g_strdup_printf("a%s", dict_signature);*/
          /*g_free(dict_signature);*/
        /*}*/
        /*JSPropertyNameArrayRelease(propnames);*/
        /*break;*/
      }

    case kJSTypeUndefined:
    case kJSTypeNull:
    default:
      g_warning("Signature lookup failed for unsupported type %i", JSValueGetType(ctx, jsvalue));
      break;
  }
  return NULL;
}
示例#3
0
文件: main.c 项目: gsnewmark/planck
JSValueRef function_set_exit_value(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
		size_t argc, const JSValueRef args[], JSValueRef* exception) {
	if (argc == 1 && JSValueGetType (ctx, args[0]) == kJSTypeNumber) {
		exit_value = JSValueToNumber(ctx, args[0], NULL);
	}
	return JSValueMakeNull(ctx);
}
示例#4
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_read_file(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                              size_t argc, const JSValueRef args[], JSValueRef *exception) {
    // TODO: implement fully

    if (argc == 1 && JSValueGetType(ctx, args[0]) == kJSTypeString) {
        char path[100];
        JSStringRef path_str = JSValueToStringCopy(ctx, args[0], NULL);
        assert(JSStringGetLength(path_str) < 100);
        JSStringGetUTF8CString(path_str, path, 100);
        JSStringRelease(path_str);

        // debug_print_value("read_file", ctx, args[0]);

        time_t last_modified = 0;
        char *contents = get_contents(path, &last_modified);
        if (contents != NULL) {
            JSStringRef contents_str = JSStringCreateWithUTF8CString(contents);
            free(contents);

            JSValueRef res[2];
            res[0] = JSValueMakeString(ctx, contents_str);
            res[1] = JSValueMakeNumber(ctx, last_modified);
            return JSObjectMakeArray(ctx, 2, res, NULL);
        }
    }

    return JSValueMakeNull(ctx);
}
示例#5
0
文件: main.c 项目: gsnewmark/planck
JSValueRef function_import_script(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
		size_t argc, const JSValueRef args[], JSValueRef* exception) {
	if (argc == 1 && JSValueGetType(ctx, args[0]) == kJSTypeString) {
		JSStringRef path_str_ref = JSValueToStringCopy(ctx, args[0], NULL);
		assert(JSStringGetLength(path_str_ref) < 100);
		char tmp[100];
		tmp[0] = '\0';
		JSStringGetUTF8CString(path_str_ref, tmp, 100);
		JSStringRelease(path_str_ref);

		char *path = tmp;
		if (str_has_prefix(path, "goog/../") == 0) {
			path = path + 8;
		}

		char *source = NULL;
		if (out_path == NULL) {
			source = bundle_get_contents(path);
		} else {
			char *full_path = str_concat(out_path, path);
			source = get_contents(full_path, NULL);
			free(full_path);
		}

		if (source != NULL) {
			evaluate_script(ctx, source, path);
			free(source);
		}
	}

	return JSValueMakeUndefined(ctx);
}
示例#6
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_input_stream_read(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                           size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *descriptor = value_to_c_string(ctx, args[0]);

        size_t buf_size = 4096;
        uint8_t *buf = malloc(buf_size * sizeof(uint8_t));

        size_t read = file_read(descriptor_str_to_int(descriptor), buf_size, buf);

        free(descriptor);

        JSValueRef arguments[read];
        int num_arguments = (int) read;
        for (int i = 0; i < num_arguments; i++) {
            arguments[i] = JSValueMakeNumber(ctx, buf[i]);
        }

        return JSObjectMakeArray(ctx, num_arguments, arguments, NULL);
    }

    return JSValueMakeNull(ctx);
}
/*
 * Converts an argument to a string.
 *
 * Convert a JSValueRef argument to a g_malloc'd gchar string. Calling function
 * is responsible for g_freeing the string.
 */
static gchar *
arg_to_string(JSContextRef context, JSValueRef arg, JSValueRef *exception) {
	JSStringRef string;
	size_t size;
	gchar *result;

	if (JSValueGetType(context, arg) != kJSTypeString) {
		_mkexception(context, exception, EXPECTSTRING);

		return NULL;
	}

	string = JSValueToStringCopy(context, arg, exception);

	if (!string) {

		return NULL;
	}

	size = JSStringGetMaximumUTF8CStringSize(string);
	result = g_malloc(size);

	if (!result) {

		return NULL;
	}

	JSStringGetUTF8CString(string, result, size);
	JSStringRelease(string);

	return result;
}
示例#8
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_writer_write(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                      size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 2
        && JSValueGetType(ctx, args[0]) == kJSTypeString
        && JSValueGetType(ctx, args[1]) == kJSTypeString) {

        char *descriptor = value_to_c_string(ctx, args[0]);
        JSStringRef str_ref = JSValueToStringCopy(ctx, args[1], NULL);

        ufile_write(descriptor_str_to_int(descriptor), str_ref);

        free(descriptor);
        JSStringRelease(str_ref);
    }

    return JSValueMakeNull(ctx);
}
JNIEXPORT jint JNICALL WebKit_win32_NATIVE(JSValueGetType)
	(JNIEnv *env, jclass that, jintLong arg0, jintLong arg1)
{
	jint rc = 0;
	WebKit_win32_NATIVE_ENTER(env, that, JSValueGetType_FUNC);
	rc = (jint)JSValueGetType((JSContextRef)arg0, (JSValueRef)arg1);
	WebKit_win32_NATIVE_EXIT(env, that, JSValueGetType_FUNC);
	return rc;
}
示例#10
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_raw_write_stderr(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                     size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1 && JSValueGetType(ctx, args[0]) == kJSTypeString) {
        char *s = value_to_c_string(ctx, args[0]);
        fprintf(stderr, "%s", s);
        free(s);
    }

    return JSValueMakeNull(ctx);
}
示例#11
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_eval(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                         size_t argc, const JSValueRef args[], JSValueRef *exception) {
    JSValueRef val = NULL;

    if (argc == 2
        && JSValueGetType(ctx, args[0]) == kJSTypeString
        && JSValueGetType(ctx, args[1]) == kJSTypeString) {
        // debug_print_value("eval", ctx, args[0]);

        JSStringRef sourceRef = JSValueToStringCopy(ctx, args[0], NULL);
        JSStringRef pathRef = JSValueToStringCopy(ctx, args[1], NULL);

        JSEvaluateScript(ctx, sourceRef, NULL, pathRef, 0, &val);

        JSStringRelease(pathRef);
        JSStringRelease(sourceRef);
    }

    return val != NULL ? val : JSValueMakeNull(ctx);
}
示例#12
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_output_stream_close(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                             size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *descriptor = value_to_c_string(ctx, args[0]);
        file_close(descriptor_str_to_int(descriptor));
        free(descriptor);
    }
    return JSValueMakeNull(ctx);
}
示例#13
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_delete_file(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *path = value_to_c_string(ctx, args[0]);
        remove(path);
        free(path);
    }
    return JSValueMakeNull(ctx);
}
int pdf_jsimp_to_type(pdf_jsimp *imp, pdf_jsimp_obj *obj)
{
	switch (JSValueGetType(imp->jscore_ctx, obj->ref))
	{
		case kJSTypeNull: return JS_TYPE_NULL;
		case kJSTypeBoolean: return JS_TYPE_BOOLEAN;
		case kJSTypeNumber: return JS_TYPE_NUMBER;
		case kJSTypeString: return JS_TYPE_STRING;
		case kJSTypeObject: return JS_TYPE_ARRAY;
		default: return JS_TYPE_UNKNOWN;
	}
}
示例#15
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_output_stream_open(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                            size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 2
        && JSValueGetType(ctx, args[0]) == kJSTypeString
        && JSValueGetType(ctx, args[1]) == kJSTypeBoolean) {

        char *path = value_to_c_string(ctx, args[0]);
        bool append = JSValueToBoolean(ctx, args[1]);

        uint64_t descriptor = file_open_write(path, append);

        free(path);

        char *descriptor_str = descriptor_int_to_str(descriptor);
        JSValueRef rv = c_string_to_value(ctx, descriptor_str);
        free(descriptor_str);

        return rv;
    }

    return JSValueMakeNull(ctx);
}
示例#16
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_list_files(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                               size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *path = value_to_c_string(ctx, args[0]);

        size_t capacity = 32;
        size_t count = 0;
        JSValueRef *paths = malloc(capacity * sizeof(paths));

        DIR *d;
        struct dirent *dir;
        d = opendir(path);

        size_t path_len = strlen(path);
        if (path_len && path[path_len - 1] == '/') {
            path[--path_len] = 0;
        }

        if (d) {
            while ((dir = readdir(d)) != NULL) {
                if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..")) {

                    char *buf = malloc((path_len + strlen(dir->d_name) + 2));
                    sprintf(buf, "%s/%s", path, dir->d_name);
                    paths[count++] = c_string_to_value(ctx, buf);
                    free(buf);

                    if (count == capacity) {
                        capacity *= 2;
                        paths = realloc(paths, capacity * sizeof(paths));
                    }
                }
            }

            closedir(d);
        }

        free(path);

        JSValueRef rv = JSObjectMakeArray(ctx, count, paths, NULL);
        free(paths);

        return rv;
    }
    return JSValueMakeNull(ctx);
}
示例#17
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_set_timeout(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeNumber) {

        int millis = (int) JSValueToNumber(ctx, args[0], NULL);

        struct timeout_data_t *timeout_data = malloc(sizeof(struct timeout_data_t));
        timeout_data->id = ++timeout_id;
        JSValueRef rv = timeout_data_to_js_value(ctx, timeout_data);

        start_timer(millis, do_run_timeout, (void *) timeout_data);

        return rv;
    }
    return JSValueMakeNull(ctx);
}
示例#18
0
static JSValueRef
set_can_register_cb (JSContextRef     js_context,
                     JSObjectRef      js_function,
                     JSObjectRef      js_this,
                     size_t           argument_count,
                     const JSValueRef js_arguments[],
                     JSValueRef*      js_exception)
{
  JSValueRef js_value = JSValueMakeNull (js_context);

  if (argument_count == 1
    && JSValueGetType (js_context, js_arguments[0]) == kJSTypeBoolean)
    {
      bool sensitive = JSValueToBoolean (js_context, js_arguments[0]);
      gtk_widget_set_sensitive (register_button, sensitive == true);
    }

  return js_value;
}
示例#19
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_import_script(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                  size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1 && JSValueGetType(ctx, args[0]) == kJSTypeString) {
        JSStringRef path_str_ref = JSValueToStringCopy(ctx, args[0], NULL);
        assert(JSStringGetLength(path_str_ref) < 100);
        char tmp[100];
        tmp[0] = '\0';
        JSStringGetUTF8CString(path_str_ref, tmp, 100);
        JSStringRelease(path_str_ref);

        bool can_skip_load = false;
        char *path = tmp;
        if (str_has_prefix(path, "goog/../") == 0) {
            path = path + 8;
        } else {
            unsigned long h = hash((unsigned char *) path);
            if (is_loaded(h)) {
                can_skip_load = true;
            } else {
                add_loaded_hash(h);
            }
        }

        if (!can_skip_load) {
            char *source = NULL;
            if (config.out_path == NULL) {
                source = bundle_get_contents(path);
            } else {
                char *full_path = str_concat(config.out_path, path);
                source = get_contents(full_path, NULL);
                free(full_path);
            }

            if (source != NULL) {
                evaluate_script(ctx, source, path);
                display_launch_timing(path);
                free(source);
            }
        }
    }

    return JSValueMakeUndefined(ctx);
}
示例#20
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_cache(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                          size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 4 &&
        JSValueGetType(ctx, args[0]) == kJSTypeString &&
        JSValueGetType(ctx, args[1]) == kJSTypeString &&
        (JSValueGetType(ctx, args[2]) == kJSTypeString
         || JSValueGetType(ctx, args[2]) == kJSTypeNull) &&
        (JSValueGetType(ctx, args[3]) == kJSTypeString
         || JSValueGetType(ctx, args[3]) == kJSTypeNull)) {
        // debug_print_value("cache", ctx, args[0]);

        char *cache_prefix = value_to_c_string(ctx, args[0]);
        char *source = value_to_c_string(ctx, args[1]);
        char *cache = value_to_c_string(ctx, args[2]);
        char *sourcemap = value_to_c_string(ctx, args[3]);

        char *suffix = NULL;
        int max_suffix_len = 20;
        size_t prefix_len = strlen(cache_prefix);
        char *path = malloc((prefix_len + max_suffix_len) * sizeof(char));
        memset(path, 0, prefix_len + max_suffix_len);

        suffix = ".js";
        strcpy(path, cache_prefix);
        strcat(path, suffix);
        write_contents(path, source);

        suffix = ".cache.json";
        strcpy(path, cache_prefix);
        strcat(path, suffix);
        write_contents(path, cache);

        suffix = ".js.map.json";
        strcpy(path, cache_prefix);
        strcat(path, suffix);
        if (sourcemap) {
            write_contents(path, sourcemap);
        }

        free(cache_prefix);
        free(source);
        free(cache);
        free(sourcemap);

        free(path);
    }

    return JSValueMakeNull(ctx);
}
示例#21
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_reader_open(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                     size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 2
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *path = value_to_c_string(ctx, args[0]);
        char *encoding = value_to_c_string(ctx, args[1]);

        uint64_t descriptor = ufile_open_read(path, encoding);

        free(path);
        free(encoding);

        char *descriptor_str = descriptor_int_to_str(descriptor);
        JSValueRef rv = c_string_to_value(ctx, descriptor_str);
        free(descriptor_str);

        return rv;
    }

    return JSValueMakeNull(ctx);
}
示例#22
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_read_password(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                  size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *prompt = value_to_c_string(ctx, args[0]);

        char *pass = getpass(prompt);

        JSValueRef rv;

        if (pass) {
            rv = c_string_to_value(ctx, pass);
            memset(pass, 0, strlen(pass));
        } else {
            rv = JSValueMakeNull(ctx);
        }

        free(prompt);
        return rv;
    }
    return JSValueMakeNull(ctx);
}
示例#23
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_is_directory(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                 size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *path = value_to_c_string(ctx, args[0]);

        bool is_directory = false;

        struct stat file_stat;

        int retval = stat(path, &file_stat);

        free(path);

        if (retval == 0) {
            is_directory = S_ISDIR(file_stat.st_mode);
        }

        return JSValueMakeBoolean(ctx, is_directory);

    }
    return JSValueMakeNull(ctx);
}
示例#24
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_file_reader_read(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                                     size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *descriptor = value_to_c_string(ctx, args[0]);

        JSStringRef result = ufile_read(descriptor_str_to_int(descriptor));

        free(descriptor);

        JSValueRef arguments[2];
        if (result != NULL) {
            arguments[0] = JSValueMakeString(ctx, result);
            JSStringRelease(result);
        } else {
            arguments[0] = JSValueMakeNull(ctx);
        }
        arguments[1] = JSValueMakeNull(ctx);
        return JSObjectMakeArray(ctx, 2, arguments, NULL);
    }

    return JSValueMakeNull(ctx);
}
static void get_javascript_result(
    GObject *object,
    GAsyncResult *result,
    gpointer user_data)
{
  g_printf("Here? Surely?\n");
  WebKitJavascriptResult *js_result;
  JSValueRef              value;
  JSGlobalContextRef      context;
  GError                 *error = NULL;

  js_result = webkit_web_view_run_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error);
  if (!js_result) {
    g_warning ("Error running javascript: %s", error->message);
    g_error_free (error);
    return;
  }

  g_printf("I'm here innit 1\n");
  context = webkit_javascript_result_get_global_context (js_result);
  g_printf("I'm here innit 2\n");
  value = webkit_javascript_result_get_value (js_result);
  int value_type = JSValueGetType(context, value);
  switch (value_type) {
    case kJSTypeUndefined:
      g_printf("Value undefined!\n");
      break;
    case kJSTypeNull:
      g_printf("Value null!\n");
      break;
    case kJSTypeBoolean:
      g_printf("Value boolean!\n");
      break;
    case kJSTypeNumber:
      g_printf("Value number!\n");
      break;
    case kJSTypeString:
      g_printf("Value string!\n");
      break;
    case kJSTypeObject:
      g_printf("Value object!\n");
      break;
  }

  if (JSValueIsString (context, value)) {
    g_printf("I'm here innit 3\n");
    JSStringRef js_str_value = JSValueToStringCopy(context, value, NULL);
    gsize       str_length = JSStringGetMaximumUTF8CStringSize(js_str_value);
    gchar      *str_value;

    g_printf("String length: %d\n", str_length);
    str_value = (gchar *)g_malloc (str_length);
    JSStringGetUTF8CString (js_str_value, str_value, str_length);
    JSStringRelease (js_str_value);

    g_print ("Script result: %s\n", str_value);
    g_free (str_value);
  } else {
    g_warning ("Error running javascript: unexpected return value");
  }
  webkit_javascript_result_unref (js_result);
}
示例#26
0
文件: testapi.c 项目: acss/owb-mirror
int main(int argc, char* argv[])
{
    const char *scriptPath = "testapi.js";
    if (argc > 1) {
        scriptPath = argv[1];
    }
    
    // Test garbage collection with a fresh context
    context = JSGlobalContextCreateInGroup(NULL, NULL);
    TestInitializeFinalize = true;
    testInitializeFinalize();
    JSGlobalContextRelease(context);
    TestInitializeFinalize = false;

    ASSERT(Base_didFinalize);

    JSClassDefinition globalObjectClassDefinition = kJSClassDefinitionEmpty;
    globalObjectClassDefinition.initialize = globalObject_initialize;
    globalObjectClassDefinition.staticValues = globalObject_staticValues;
    globalObjectClassDefinition.staticFunctions = globalObject_staticFunctions;
    globalObjectClassDefinition.attributes = kJSClassAttributeNoAutomaticPrototype;
    JSClassRef globalObjectClass = JSClassCreate(&globalObjectClassDefinition);
    context = JSGlobalContextCreateInGroup(NULL, globalObjectClass);

    JSGlobalContextRetain(context);
    JSGlobalContextRelease(context);

    JSObjectRef globalObject = JSContextGetGlobalObject(context);
    ASSERT(JSValueIsObject(context, globalObject));
    
    JSValueRef jsUndefined = JSValueMakeUndefined(context);
    JSValueRef jsNull = JSValueMakeNull(context);
    JSValueRef jsTrue = JSValueMakeBoolean(context, true);
    JSValueRef jsFalse = JSValueMakeBoolean(context, false);
    JSValueRef jsZero = JSValueMakeNumber(context, 0);
    JSValueRef jsOne = JSValueMakeNumber(context, 1);
    JSValueRef jsOneThird = JSValueMakeNumber(context, 1.0 / 3.0);
    JSObjectRef jsObjectNoProto = JSObjectMake(context, NULL, NULL);
    JSObjectSetPrototype(context, jsObjectNoProto, JSValueMakeNull(context));

    // FIXME: test funny utf8 characters
    JSStringRef jsEmptyIString = JSStringCreateWithUTF8CString("");
    JSValueRef jsEmptyString = JSValueMakeString(context, jsEmptyIString);
    
    JSStringRef jsOneIString = JSStringCreateWithUTF8CString("1");
    JSValueRef jsOneString = JSValueMakeString(context, jsOneIString);

    UniChar singleUniChar = 65; // Capital A
    CFMutableStringRef cfString = 
        CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorDefault,
                                                          &singleUniChar,
                                                          1,
                                                          1,
                                                          kCFAllocatorNull);

    JSStringRef jsCFIString = JSStringCreateWithCFString(cfString);
    JSValueRef jsCFString = JSValueMakeString(context, jsCFIString);
    
    CFStringRef cfEmptyString = CFStringCreateWithCString(kCFAllocatorDefault, "", kCFStringEncodingUTF8);
    
    JSStringRef jsCFEmptyIString = JSStringCreateWithCFString(cfEmptyString);
    JSValueRef jsCFEmptyString = JSValueMakeString(context, jsCFEmptyIString);

    CFIndex cfStringLength = CFStringGetLength(cfString);
    UniChar* buffer = (UniChar*)malloc(cfStringLength * sizeof(UniChar));
    CFStringGetCharacters(cfString, 
                          CFRangeMake(0, cfStringLength), 
                          buffer);
    JSStringRef jsCFIStringWithCharacters = JSStringCreateWithCharacters((JSChar*)buffer, cfStringLength);
    JSValueRef jsCFStringWithCharacters = JSValueMakeString(context, jsCFIStringWithCharacters);
    
    JSStringRef jsCFEmptyIStringWithCharacters = JSStringCreateWithCharacters((JSChar*)buffer, CFStringGetLength(cfEmptyString));
    free(buffer);
    JSValueRef jsCFEmptyStringWithCharacters = JSValueMakeString(context, jsCFEmptyIStringWithCharacters);

    ASSERT(JSValueGetType(context, jsUndefined) == kJSTypeUndefined);
    ASSERT(JSValueGetType(context, jsNull) == kJSTypeNull);
    ASSERT(JSValueGetType(context, jsTrue) == kJSTypeBoolean);
    ASSERT(JSValueGetType(context, jsFalse) == kJSTypeBoolean);
    ASSERT(JSValueGetType(context, jsZero) == kJSTypeNumber);
    ASSERT(JSValueGetType(context, jsOne) == kJSTypeNumber);
    ASSERT(JSValueGetType(context, jsOneThird) == kJSTypeNumber);
    ASSERT(JSValueGetType(context, jsEmptyString) == kJSTypeString);
    ASSERT(JSValueGetType(context, jsOneString) == kJSTypeString);
    ASSERT(JSValueGetType(context, jsCFString) == kJSTypeString);
    ASSERT(JSValueGetType(context, jsCFStringWithCharacters) == kJSTypeString);
    ASSERT(JSValueGetType(context, jsCFEmptyString) == kJSTypeString);
    ASSERT(JSValueGetType(context, jsCFEmptyStringWithCharacters) == kJSTypeString);

    JSObjectRef myObject = JSObjectMake(context, MyObject_class(context), NULL);
    JSStringRef myObjectIString = JSStringCreateWithUTF8CString("MyObject");
    JSObjectSetProperty(context, globalObject, myObjectIString, myObject, kJSPropertyAttributeNone, NULL);
    JSStringRelease(myObjectIString);
    
    JSValueRef exception;

    // Conversions that throw exceptions
    exception = NULL;
    ASSERT(NULL == JSValueToObject(context, jsNull, &exception));
    ASSERT(exception);
    
    exception = NULL;
    // FIXME <rdar://4668451> - On i386 the isnan(double) macro tries to map to the isnan(float) function,
    // causing a build break with -Wshorten-64-to-32 enabled.  The issue is known by the appropriate team.
    // After that's resolved, we can remove these casts
    ASSERT(isnan((float)JSValueToNumber(context, jsObjectNoProto, &exception)));
    ASSERT(exception);

    exception = NULL;
    ASSERT(!JSValueToStringCopy(context, jsObjectNoProto, &exception));
    ASSERT(exception);
    
    ASSERT(JSValueToBoolean(context, myObject));
    
    exception = NULL;
    ASSERT(!JSValueIsEqual(context, jsObjectNoProto, JSValueMakeNumber(context, 1), &exception));
    ASSERT(exception);
    
    exception = NULL;
    JSObjectGetPropertyAtIndex(context, myObject, 0, &exception);
    ASSERT(1 == JSValueToNumber(context, exception, NULL));

    assertEqualsAsBoolean(jsUndefined, false);
    assertEqualsAsBoolean(jsNull, false);
    assertEqualsAsBoolean(jsTrue, true);
    assertEqualsAsBoolean(jsFalse, false);
    assertEqualsAsBoolean(jsZero, false);
    assertEqualsAsBoolean(jsOne, true);
    assertEqualsAsBoolean(jsOneThird, true);
    assertEqualsAsBoolean(jsEmptyString, false);
    assertEqualsAsBoolean(jsOneString, true);
    assertEqualsAsBoolean(jsCFString, true);
    assertEqualsAsBoolean(jsCFStringWithCharacters, true);
    assertEqualsAsBoolean(jsCFEmptyString, false);
    assertEqualsAsBoolean(jsCFEmptyStringWithCharacters, false);
    
    assertEqualsAsNumber(jsUndefined, nan(""));
    assertEqualsAsNumber(jsNull, 0);
    assertEqualsAsNumber(jsTrue, 1);
    assertEqualsAsNumber(jsFalse, 0);
    assertEqualsAsNumber(jsZero, 0);
    assertEqualsAsNumber(jsOne, 1);
    assertEqualsAsNumber(jsOneThird, 1.0 / 3.0);
    assertEqualsAsNumber(jsEmptyString, 0);
    assertEqualsAsNumber(jsOneString, 1);
    assertEqualsAsNumber(jsCFString, nan(""));
    assertEqualsAsNumber(jsCFStringWithCharacters, nan(""));
    assertEqualsAsNumber(jsCFEmptyString, 0);
    assertEqualsAsNumber(jsCFEmptyStringWithCharacters, 0);
    ASSERT(sizeof(JSChar) == sizeof(UniChar));
    
    assertEqualsAsCharactersPtr(jsUndefined, "undefined");
    assertEqualsAsCharactersPtr(jsNull, "null");
    assertEqualsAsCharactersPtr(jsTrue, "true");
    assertEqualsAsCharactersPtr(jsFalse, "false");
    assertEqualsAsCharactersPtr(jsZero, "0");
    assertEqualsAsCharactersPtr(jsOne, "1");
    assertEqualsAsCharactersPtr(jsOneThird, "0.3333333333333333");
    assertEqualsAsCharactersPtr(jsEmptyString, "");
    assertEqualsAsCharactersPtr(jsOneString, "1");
    assertEqualsAsCharactersPtr(jsCFString, "A");
    assertEqualsAsCharactersPtr(jsCFStringWithCharacters, "A");
    assertEqualsAsCharactersPtr(jsCFEmptyString, "");
    assertEqualsAsCharactersPtr(jsCFEmptyStringWithCharacters, "");
    
    assertEqualsAsUTF8String(jsUndefined, "undefined");
    assertEqualsAsUTF8String(jsNull, "null");
    assertEqualsAsUTF8String(jsTrue, "true");
    assertEqualsAsUTF8String(jsFalse, "false");
    assertEqualsAsUTF8String(jsZero, "0");
    assertEqualsAsUTF8String(jsOne, "1");
    assertEqualsAsUTF8String(jsOneThird, "0.3333333333333333");
    assertEqualsAsUTF8String(jsEmptyString, "");
    assertEqualsAsUTF8String(jsOneString, "1");
    assertEqualsAsUTF8String(jsCFString, "A");
    assertEqualsAsUTF8String(jsCFStringWithCharacters, "A");
    assertEqualsAsUTF8String(jsCFEmptyString, "");
    assertEqualsAsUTF8String(jsCFEmptyStringWithCharacters, "");
    
    ASSERT(JSValueIsStrictEqual(context, jsTrue, jsTrue));
    ASSERT(!JSValueIsStrictEqual(context, jsOne, jsOneString));

    ASSERT(JSValueIsEqual(context, jsOne, jsOneString, NULL));
    ASSERT(!JSValueIsEqual(context, jsTrue, jsFalse, NULL));
    
    CFStringRef cfJSString = JSStringCopyCFString(kCFAllocatorDefault, jsCFIString);
    CFStringRef cfJSEmptyString = JSStringCopyCFString(kCFAllocatorDefault, jsCFEmptyIString);
    ASSERT(CFEqual(cfJSString, cfString));
    ASSERT(CFEqual(cfJSEmptyString, cfEmptyString));
    CFRelease(cfJSString);
    CFRelease(cfJSEmptyString);

    CFRelease(cfString);
    CFRelease(cfEmptyString);
    
    jsGlobalValue = JSObjectMake(context, NULL, NULL);
    JSValueProtect(context, jsGlobalValue);
    JSGarbageCollect(context);
    ASSERT(JSValueIsObject(context, jsGlobalValue));
    JSValueUnprotect(context, jsGlobalValue);

    JSStringRef goodSyntax = JSStringCreateWithUTF8CString("x = 1;");
    JSStringRef badSyntax = JSStringCreateWithUTF8CString("x := 1;");
    ASSERT(JSCheckScriptSyntax(context, goodSyntax, NULL, 0, NULL));
    ASSERT(!JSCheckScriptSyntax(context, badSyntax, NULL, 0, NULL));

    JSValueRef result;
    JSValueRef v;
    JSObjectRef o;
    JSStringRef string;

    result = JSEvaluateScript(context, goodSyntax, NULL, NULL, 1, NULL);
    ASSERT(result);
    ASSERT(JSValueIsEqual(context, result, jsOne, NULL));

    exception = NULL;
    result = JSEvaluateScript(context, badSyntax, NULL, NULL, 1, &exception);
    ASSERT(!result);
    ASSERT(JSValueIsObject(context, exception));
    
    JSStringRef array = JSStringCreateWithUTF8CString("Array");
    JSObjectRef arrayConstructor = JSValueToObject(context, JSObjectGetProperty(context, globalObject, array, NULL), NULL);
    JSStringRelease(array);
    result = JSObjectCallAsConstructor(context, arrayConstructor, 0, NULL, NULL);
    ASSERT(result);
    ASSERT(JSValueIsObject(context, result));
    ASSERT(JSValueIsInstanceOfConstructor(context, result, arrayConstructor, NULL));
    ASSERT(!JSValueIsInstanceOfConstructor(context, JSValueMakeNull(context), arrayConstructor, NULL));

    o = JSValueToObject(context, result, NULL);
    exception = NULL;
    ASSERT(JSValueIsUndefined(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception)));
    ASSERT(!exception);
    
    JSObjectSetPropertyAtIndex(context, o, 0, JSValueMakeNumber(context, 1), &exception);
    ASSERT(!exception);
    
    exception = NULL;
    ASSERT(1 == JSValueToNumber(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception), &exception));
    ASSERT(!exception);

    JSStringRef functionBody;
    JSObjectRef function;
    
    exception = NULL;
    functionBody = JSStringCreateWithUTF8CString("rreturn Array;");
    JSStringRef line = JSStringCreateWithUTF8CString("line");
    ASSERT(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception));
    ASSERT(JSValueIsObject(context, exception));
    v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL);
    assertEqualsAsNumber(v, 1);
    JSStringRelease(functionBody);
    JSStringRelease(line);

    exception = NULL;
    functionBody = JSStringCreateWithUTF8CString("return Array;");
    function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception);
    JSStringRelease(functionBody);
    ASSERT(!exception);
    ASSERT(JSObjectIsFunction(context, function));
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
    ASSERT(v);
    ASSERT(JSValueIsEqual(context, v, arrayConstructor, NULL));
    
    exception = NULL;
    function = JSObjectMakeFunction(context, NULL, 0, NULL, jsEmptyIString, NULL, 0, &exception);
    ASSERT(!exception);
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, &exception);
    ASSERT(v && !exception);
    ASSERT(JSValueIsUndefined(context, v));
    
    exception = NULL;
    v = NULL;
    JSStringRef foo = JSStringCreateWithUTF8CString("foo");
    JSStringRef argumentNames[] = { foo };
    functionBody = JSStringCreateWithUTF8CString("return foo;");
    function = JSObjectMakeFunction(context, foo, 1, argumentNames, functionBody, NULL, 1, &exception);
    ASSERT(function && !exception);
    JSValueRef arguments[] = { JSValueMakeNumber(context, 2) };
    v = JSObjectCallAsFunction(context, function, NULL, 1, arguments, &exception);
    JSStringRelease(foo);
    JSStringRelease(functionBody);
    
    string = JSValueToStringCopy(context, function, NULL);
    assertEqualsAsUTF8String(JSValueMakeString(context, string), "function foo(foo) {return foo;}");
    JSStringRelease(string);

    JSStringRef print = JSStringCreateWithUTF8CString("print");
    JSObjectRef printFunction = JSObjectMakeFunctionWithCallback(context, print, print_callAsFunction);
    JSObjectSetProperty(context, globalObject, print, printFunction, kJSPropertyAttributeNone, NULL); 
    JSStringRelease(print);
    
    ASSERT(!JSObjectSetPrivate(printFunction, (void*)1));
    ASSERT(!JSObjectGetPrivate(printFunction));

    JSStringRef myConstructorIString = JSStringCreateWithUTF8CString("MyConstructor");
    JSObjectRef myConstructor = JSObjectMakeConstructor(context, NULL, myConstructor_callAsConstructor);
    JSObjectSetProperty(context, globalObject, myConstructorIString, myConstructor, kJSPropertyAttributeNone, NULL);
    JSStringRelease(myConstructorIString);
    
    ASSERT(!JSObjectSetPrivate(myConstructor, (void*)1));
    ASSERT(!JSObjectGetPrivate(myConstructor));
    
    string = JSStringCreateWithUTF8CString("Derived");
    JSObjectRef derivedConstructor = JSObjectMakeConstructor(context, Derived_class(context), NULL);
    JSObjectSetProperty(context, globalObject, string, derivedConstructor, kJSPropertyAttributeNone, NULL);
    JSStringRelease(string);
    
    o = JSObjectMake(context, NULL, NULL);
    JSObjectSetProperty(context, o, jsOneIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeNone, NULL);
    JSObjectSetProperty(context, o, jsCFIString,  JSValueMakeNumber(context, 1), kJSPropertyAttributeDontEnum, NULL);
    JSPropertyNameArrayRef nameArray = JSObjectCopyPropertyNames(context, o);
    size_t expectedCount = JSPropertyNameArrayGetCount(nameArray);
    size_t count;
    for (count = 0; count < expectedCount; ++count)
        JSPropertyNameArrayGetNameAtIndex(nameArray, count);
    JSPropertyNameArrayRelease(nameArray);
    ASSERT(count == 1); // jsCFString should not be enumerated

    JSClassDefinition nullDefinition = kJSClassDefinitionEmpty;
    nullDefinition.attributes = kJSClassAttributeNoAutomaticPrototype;
    JSClassRef nullClass = JSClassCreate(&nullDefinition);
    JSClassRelease(nullClass);
    
    nullDefinition = kJSClassDefinitionEmpty;
    nullClass = JSClassCreate(&nullDefinition);
    JSClassRelease(nullClass);

    functionBody = JSStringCreateWithUTF8CString("return this;");
    function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL);
    JSStringRelease(functionBody);
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
    ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
    v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL);
    ASSERT(JSValueIsEqual(context, v, o, NULL));

    functionBody = JSStringCreateWithUTF8CString("return eval(\"this\");");
    function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL);
    JSStringRelease(functionBody);
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
    ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
    v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL);
    ASSERT(JSValueIsEqual(context, v, o, NULL));

    JSStringRef script = JSStringCreateWithUTF8CString("this;");
    v = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
    ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
    v = JSEvaluateScript(context, script, o, NULL, 1, NULL);
    ASSERT(JSValueIsEqual(context, v, o, NULL));
    JSStringRelease(script);

    script = JSStringCreateWithUTF8CString("eval(this);");
    v = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
    ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
    v = JSEvaluateScript(context, script, o, NULL, 1, NULL);
    ASSERT(JSValueIsEqual(context, v, o, NULL));
    JSStringRelease(script);

    char* scriptUTF8 = createStringWithContentsOfFile(scriptPath);
    if (!scriptUTF8)
        printf("FAIL: Test script could not be loaded.\n");
    else {
        script = JSStringCreateWithUTF8CString(scriptUTF8);
        result = JSEvaluateScript(context, script, NULL, NULL, 1, &exception);
        if (JSValueIsUndefined(context, result))
            printf("PASS: Test script executed successfully.\n");
        else {
            printf("FAIL: Test script returned unexpected value:\n");
            JSStringRef exceptionIString = JSValueToStringCopy(context, exception, NULL);
            CFStringRef exceptionCF = JSStringCopyCFString(kCFAllocatorDefault, exceptionIString);
            CFShow(exceptionCF);
            CFRelease(exceptionCF);
            JSStringRelease(exceptionIString);
        }
        JSStringRelease(script);
        free(scriptUTF8);
    }

    // Clear out local variables pointing at JSObjectRefs to allow their values to be collected
    function = NULL;
    v = NULL;
    o = NULL;
    globalObject = NULL;

    JSStringRelease(jsEmptyIString);
    JSStringRelease(jsOneIString);
    JSStringRelease(jsCFIString);
    JSStringRelease(jsCFEmptyIString);
    JSStringRelease(jsCFIStringWithCharacters);
    JSStringRelease(jsCFEmptyIStringWithCharacters);
    JSStringRelease(goodSyntax);
    JSStringRelease(badSyntax);

    JSGlobalContextRelease(context);
    JSClassRelease(globalObjectClass);

    printf("PASS: Program exited normally.\n");
    return 0;
}
示例#27
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_fstat(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                          size_t argc, const JSValueRef args[], JSValueRef *exception) {
    if (argc == 1
        && JSValueGetType(ctx, args[0]) == kJSTypeString) {

        char *path = value_to_c_string(ctx, args[0]);

        struct stat file_stat;

        int retval = lstat(path, &file_stat);

        if (retval == 0) {
            JSObjectRef result = JSObjectMake(ctx, NULL, NULL);

            char *type = "unknown";
            if (S_ISDIR(file_stat.st_mode)) {
                type = "directory";
            } else if (S_ISREG(file_stat.st_mode)) {
                type = "file";
            } else if (S_ISLNK(file_stat.st_mode)) {
                type = "symbolic-link";
            } else if (S_ISSOCK(file_stat.st_mode)) {
                type = "socket";
            } else if (S_ISFIFO(file_stat.st_mode)) {
                type = "fifo";
            } else if (S_ISCHR(file_stat.st_mode)) {
                type = "character-special";
            } else if (S_ISBLK(file_stat.st_mode)) {
                type = "block-special";
            }

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("type"),
                                c_string_to_value(ctx, type),
                                kJSPropertyAttributeReadOnly, NULL);


            double device_id = (double) file_stat.st_rdev;
            if (device_id) {
                JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("device-id"),
                                    JSValueMakeNumber(ctx, device_id),
                                    kJSPropertyAttributeReadOnly, NULL);
            }

            double file_number = (double) file_stat.st_ino;
            if (file_number) {
                JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("file-number"),
                                    JSValueMakeNumber(ctx, file_number),
                                    kJSPropertyAttributeReadOnly, NULL);
            }

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("permissions"),
                                JSValueMakeNumber(ctx, (double) (ACCESSPERMS & file_stat.st_mode)),
                                kJSPropertyAttributeReadOnly, NULL);

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("reference-count"),
                                JSValueMakeNumber(ctx, (double) file_stat.st_nlink),
                                kJSPropertyAttributeReadOnly, NULL);

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("uid"),
                                JSValueMakeNumber(ctx, (double) file_stat.st_uid),
                                kJSPropertyAttributeReadOnly, NULL);

            struct passwd *uid_passwd = getpwuid(file_stat.st_uid);

            if (uid_passwd) {
                JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("uname"),
                                    c_string_to_value(ctx, uid_passwd->pw_name),
                                    kJSPropertyAttributeReadOnly, NULL);
            }

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("gid"),
                                JSValueMakeNumber(ctx, (double) file_stat.st_gid),
                                kJSPropertyAttributeReadOnly, NULL);

            struct group *gid_group = getgrgid(file_stat.st_gid);

            if (gid_group) {
                JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("gname"),
                                    c_string_to_value(ctx, gid_group->gr_name),
                                    kJSPropertyAttributeReadOnly, NULL);
            }

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("file-size"),
                                JSValueMakeNumber(ctx, (double) file_stat.st_size),
                                kJSPropertyAttributeReadOnly, NULL);

#ifdef __APPLE__
#define birthtime(x) x.st_birthtime
#else
#define birthtime(x) x.st_ctime
#endif

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("created"),
                                JSValueMakeNumber(ctx, 1000 * birthtime(file_stat)),
                                kJSPropertyAttributeReadOnly, NULL);

            JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("modified"),
                                JSValueMakeNumber(ctx, 1000 * file_stat.st_mtime),
                                kJSPropertyAttributeReadOnly, NULL);

            return result;
        }

        free(path);
    }
    return JSValueMakeNull(ctx);
}
示例#28
0
文件: http.c 项目: johanatan/planck
JSValueRef function_http_request(JSContextRef ctx, JSObjectRef function, JSObjectRef this_object,
		size_t argc, const JSValueRef args[], JSValueRef* exception) {
	if (argc == 1 && JSValueGetType(ctx, args[0]) == kJSTypeObject) {
		JSObjectRef opts = JSValueToObject(ctx, args[0], NULL);
		JSValueRef url_ref = JSObjectGetProperty(ctx, opts, JSStringCreateWithUTF8CString("url"), NULL);
		char *url = value_to_c_string(ctx, url_ref);
		JSValueRef timeout_ref = JSObjectGetProperty(ctx, opts, JSStringCreateWithUTF8CString("timeout"), NULL);
		time_t timeout = 0;
		if (JSValueIsNumber(ctx, timeout_ref)) {
			timeout = (time_t) JSValueToNumber(ctx, timeout_ref, NULL);
		}
		JSValueRef method_ref = JSObjectGetProperty(ctx, opts, JSStringCreateWithUTF8CString("method"), NULL);
		char *method = value_to_c_string(ctx, method_ref);
		JSValueRef body_ref = JSObjectGetProperty(ctx, opts, JSStringCreateWithUTF8CString("body"), NULL);

		JSObjectRef headers_obj = JSValueToObject(ctx, JSObjectGetProperty(ctx, opts, JSStringCreateWithUTF8CString("headers"), NULL), NULL);

		CURL *handle = curl_easy_init();
		assert(handle != NULL);

		curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, method);
		curl_easy_setopt(handle, CURLOPT_URL, url);

		struct curl_slist *headers = NULL;
		if (!JSValueIsNull(ctx, headers_obj)) {
			JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames(ctx, headers_obj);
			size_t n = JSPropertyNameArrayGetCount(properties);
			for (int i = 0; i < n; i++) {
				JSStringRef key_str = JSPropertyNameArrayGetNameAtIndex(properties, i);
				JSValueRef val_ref = JSObjectGetProperty(ctx, headers_obj, key_str, NULL);

				size_t len = JSStringGetLength(key_str) + 1;
				char *key = malloc(len * sizeof(char));
				JSStringGetUTF8CString(key_str, key, len);
				JSStringRef val_as_str = to_string(ctx, val_ref);
				char *val = value_to_c_string(ctx, JSValueMakeString(ctx, val_as_str));
				JSStringRelease(val_as_str);

				size_t len_key = strlen(key);
				size_t len_val = strlen(val);
				char *header = malloc((len_key + len_val + 2 + 1) * sizeof(char));
				sprintf(header, "%s: %s", key, val);
				curl_slist_append(headers, header);
				free(header);

				free(key);
				free(val);
			}

			curl_easy_setopt(handle, CURLOPT_HEADER, headers);
		}

		// curl_easy_setopt(handle, CURLOPT_HEADER, 1L);
		curl_easy_setopt(handle, CURLOPT_TIMEOUT, timeout);

		struct read_string_state input_state;
		if (!JSValueIsUndefined(ctx, body_ref)) {
			char *body = value_to_c_string(ctx, body_ref);
			input_state.input = body;
			input_state.offset = 0;
			input_state.length = strlen(body);
			curl_easy_setopt(handle, CURLOPT_READDATA, &input_state);
			curl_easy_setopt(handle, CURLOPT_READFUNCTION, read_string_callback);
		}

		JSObjectRef response_headers = JSObjectMake(ctx, NULL, NULL);
		struct header_state header_state;
		header_state.ctx = ctx;
		header_state.headers = response_headers;
		curl_easy_setopt(handle, CURLOPT_HEADERDATA, &header_state);
		curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, header_to_object_callback);

		struct write_state body_state;
		body_state.offset = 0;
		body_state.length = 0;
		body_state.data = NULL;
		curl_easy_setopt(handle, CURLOPT_WRITEDATA, &body_state);
		curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_string_callback);

		JSObjectRef result = JSObjectMake(ctx, NULL, NULL);

		int res = curl_easy_perform(handle);
		if (res != 0) {
			JSStringRef error_str = JSStringCreateWithUTF8CString(curl_easy_strerror(res));
			JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("error"), JSValueMakeString(ctx, error_str), kJSPropertyAttributeReadOnly, NULL);
		}

		int status = 0;
		curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &status);

		// printf("%d bytes, %x\n", body_state.offset, body_state.data);
		if (body_state.data != NULL) {
			JSStringRef body_str = JSStringCreateWithUTF8CString(body_state.data);
			JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("body"), JSValueMakeString(ctx, body_str), kJSPropertyAttributeReadOnly, NULL);
			free(body_state.data);
		}

		JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("status"), JSValueMakeNumber(ctx, status), kJSPropertyAttributeReadOnly, NULL);
		JSObjectSetProperty(ctx, result, JSStringCreateWithUTF8CString("headers"), response_headers, kJSPropertyAttributeReadOnly, NULL);

		curl_slist_free_all(headers);
		curl_easy_cleanup(handle);

		return result;
	}

	return JSValueMakeNull(ctx);
}
示例#29
0
文件: dp_js.c 项目: dplatform/dupin
static void
js_value (JSContextRef ctx, JSValueRef value, JsonNode ** v)
{
  switch (JSValueGetType (ctx, value))
    {
    case kJSTypeUndefined:
    case kJSTypeNull:
      *v = json_node_new (JSON_NODE_NULL);

      break;

    case kJSTypeBoolean:
      *v = json_node_new (JSON_NODE_VALUE);

      json_node_set_boolean (*v,
                                 JSValueToBoolean (ctx,
                                                   value) ==
                                 true ? TRUE : FALSE);
      break;

    case kJSTypeNumber:
      *v = json_node_new (JSON_NODE_VALUE);

      json_node_set_double (*v,
                                (gdouble) JSValueToNumber (ctx, value, NULL));
      break;

    case kJSTypeString:
      {
        JSStringRef string;
        gchar *str;

        string = JSValueToStringCopy (ctx, value, NULL);
        str = js_string (string);
        JSStringRelease (string);

        *v = json_node_new (JSON_NODE_VALUE);

        json_node_set_string (*v, str);

        g_free (str);
        break;
      }

    case kJSTypeObject:
      {
        *v = json_node_new (JSON_NODE_OBJECT);
        JsonObject *o = json_object_new ();

        js_obj (ctx, JSValueToObject (ctx, value, NULL), o);

        json_node_take_object (*v, o);

        break;
      }
    }

  /* FIXME: array?!? integer?!?
            -> probably arrays are considered instances of Array() Javascript object ?!

            see http://developer.apple.com/library/mac/#documentation/Carbon/Reference/WebKit_JavaScriptCore_Ref/JSValueRef_h/index.html%23//apple_ref/c/func/JSValueGetType */

  debug_print_json_node ( "js_value(): ", *v );
}
示例#30
0
文件: functions.c 项目: mfikes/planck
JSValueRef function_load(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
                         size_t argc, const JSValueRef args[], JSValueRef *exception) {
    // TODO: implement fully

    if (argc == 1 && JSValueGetType(ctx, args[0]) == kJSTypeString) {
        char path[PATH_MAX];
        JSStringRef path_str = JSValueToStringCopy(ctx, args[0], NULL);
        assert(JSStringGetLength(path_str) < PATH_MAX);
        JSStringGetUTF8CString(path_str, path, PATH_MAX);
        JSStringRelease(path_str);

        // debug_print_value("load", ctx, args[0]);

        time_t last_modified = 0;
        char *contents = NULL;
        char *loaded_path = strdup(path);

        bool developing = (config.num_src_paths == 1 &&
                           strcmp(config.src_paths[0].type, "src") == 0 &&
                           str_has_suffix(config.src_paths[0].path, "/planck-cljs/src/") == 0);

        if (!developing) {
            contents = bundle_get_contents(path);
            last_modified = 0;
        }

        // load from classpath
        if (contents == NULL) {
            for (int i = 0; i < config.num_src_paths; i++) {
                if (config.src_paths[i].blacklisted) {
                    continue;
                }

                char *type = config.src_paths[i].type;
                char *location = config.src_paths[i].path;

                if (strcmp(type, "src") == 0) {
                    char *full_path = str_concat(location, path);
                    contents = get_contents(full_path, &last_modified);
                    if (contents != NULL) {
                        free(loaded_path);
                        loaded_path = strdup(full_path);
                    }
                    free(full_path);
                } else if (strcmp(type, "jar") == 0) {
                    struct stat file_stat;
                    if (stat(location, &file_stat) == 0) {
                        contents = get_contents_zip(location, path, &last_modified);
                    } else {
                        cljs_perror(location);
                        config.src_paths[i].blacklisted = true;
                    }
                }

                if (contents != NULL) {
                    break;
                }
            }
        }

        // load from out/
        if (contents == NULL) {
            if (config.out_path != NULL) {
                char *full_path = str_concat(config.out_path, path);
                contents = get_contents(full_path, &last_modified);
                free(full_path);
            }
        }

        if (developing && contents == NULL) {
            contents = bundle_get_contents(path);
            last_modified = 0;
        }

        if (contents != NULL) {
            JSStringRef contents_str = JSStringCreateWithUTF8CString(contents);
            free(contents);
            JSStringRef loaded_path_str = JSStringCreateWithUTF8CString(loaded_path);
            free(loaded_path);

            JSValueRef res[3];
            res[0] = JSValueMakeString(ctx, contents_str);
            res[1] = JSValueMakeNumber(ctx, last_modified);
            res[2] = JSValueMakeString(ctx, loaded_path_str);
            return JSObjectMakeArray(ctx, 3, res, NULL);
        }
    }

    return JSValueMakeNull(ctx);
}