Factor the initialisation of smjs_elinks_global out of init_smjs and
[elinks.git] / src / scripting / smjs / core.c
blob5b659d6046d15c92479f944e5444d91d68ea3c7c
1 /* ECMAScript browser scripting module */
3 #ifdef HAVE_CONFIG_H
4 #include "config.h"
5 #endif
7 #include "elinks.h"
9 #include "config/home.h"
10 #include "ecmascript/spidermonkey/util.h"
11 #include "main/module.h"
12 #include "scripting/scripting.h"
13 #include "scripting/smjs/core.h"
14 #include "scripting/smjs/elinks_object.h"
15 #include "scripting/smjs/global_object.h"
16 #include "scripting/smjs/smjs.h"
17 #include "util/string.h"
20 #define SMJS_HOOKS_FILENAME "hooks.js"
22 JSContext *smjs_ctx;
23 JSObject *smjs_elinks_object;
24 struct session *smjs_ses;
27 void
28 alert_smjs_error(unsigned char *msg)
30 report_scripting_error(&smjs_scripting_module,
31 smjs_ses, msg);
34 static void
35 error_reporter(JSContext *ctx, const char *message, JSErrorReport *report)
37 unsigned char *strict, *exception, *warning, *error;
38 struct string msg;
40 if (!init_string(&msg)) goto reported;
42 strict = JSREPORT_IS_STRICT(report->flags) ? " strict" : "";
43 exception = JSREPORT_IS_EXCEPTION(report->flags) ? " exception" : "";
44 warning = JSREPORT_IS_WARNING(report->flags) ? " warning" : "";
45 error = !report->flags ? " error" : "";
47 add_format_to_string(&msg, "A client script raised the following%s%s%s%s",
48 strict, exception, warning, error);
50 add_to_string(&msg, ":\n\n");
51 add_to_string(&msg, message);
53 if (report->linebuf && report->tokenptr) {
54 int pos = report->tokenptr - report->linebuf;
56 add_format_to_string(&msg, "\n\n%s\n.%*s^%*s.",
57 report->linebuf,
58 pos - 2, " ",
59 strlen(report->linebuf) - pos - 1, " ");
62 alert_smjs_error(msg.source);
63 done_string(&msg);
65 reported:
66 JS_ClearPendingException(ctx);
69 static JSRuntime *smjs_rt;
71 void
72 smjs_load_hooks(void)
74 jsval rval;
75 struct string script;
76 unsigned char *path;
78 assert(smjs_ctx);
80 if (!init_string(&script)) return;
82 if (elinks_home) {
83 path = straconcat(elinks_home, SMJS_HOOKS_FILENAME, NULL);
84 } else {
85 path = stracpy(CONFDIR "/" SMJS_HOOKS_FILENAME);
88 if (add_file_to_string(&script, path)
89 && JS_FALSE == JS_EvaluateScript(smjs_ctx,
90 JS_GetGlobalObject(smjs_ctx),
91 script.source, script.length, path, 1, &rval))
92 alert_smjs_error("error loading default script file");
94 mem_free(path);
95 done_string(&script);
98 void
99 init_smjs(struct module *module)
101 smjs_rt = JS_NewRuntime(1L * 1024L * 1024L);
102 if (!smjs_rt) return;
104 smjs_ctx = JS_NewContext(smjs_rt, 8192);
105 if (!smjs_ctx) {
106 JS_DestroyRuntime(smjs_rt);
107 smjs_rt = NULL;
108 return;
111 JS_SetErrorReporter(smjs_ctx, error_reporter);
113 smjs_init_global_object();
115 smjs_init_elinks_object();
117 smjs_load_hooks();
120 void
121 cleanup_smjs(struct module *module)
123 if (!smjs_ctx) return;
125 JS_DestroyContext(smjs_ctx);
126 JS_DestroyRuntime(smjs_rt);