1 /**
2 * vimb - a webkit based vim like browser.
3 *
4 * Copyright (C) 2012-2018 Daniel Carl
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see http://www.gnu.org/licenses/.
18 */
19
20 #include <glib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include "../config.h"
24 #include "ext-util.h"
25
26 /**
27 * Evaluates given string as script and return if this call succeed or not.
28 */
ext_util_js_eval(JSContextRef ctx,const char * script,JSValueRef * result)29 gboolean ext_util_js_eval(JSContextRef ctx, const char *script, JSValueRef *result)
30 {
31 JSStringRef js_str;
32 JSValueRef exc = NULL, res = NULL;
33
34 js_str = JSStringCreateWithUTF8CString(script);
35 res = JSEvaluateScript(ctx, js_str, JSContextGetGlobalObject(ctx), NULL, 0, &exc);
36 JSStringRelease(js_str);
37
38 if (exc) {
39 *result = exc;
40 return FALSE;
41 }
42
43 *result = res;
44 return TRUE;
45 }
46
47 /**
48 * Creates a temporary file with given content.
49 *
50 * Upon success, and if file is non-NULL, the actual file path used is
51 * returned in file. This string should be freed with g_free() when not
52 * needed any longer.
53 */
ext_util_create_tmp_file(const char * content,char ** file)54 gboolean ext_util_create_tmp_file(const char *content, char **file)
55 {
56 int fp;
57 ssize_t bytes, len;
58
59 fp = g_file_open_tmp(PROJECT "-XXXXXX", file, NULL);
60 if (fp == -1) {
61 g_critical("Could not create temp file %s", *file);
62 g_free(*file);
63 return FALSE;
64 }
65
66 len = strlen(content);
67
68 /* write content into temporary file */
69 bytes = write(fp, content, len);
70 if (bytes < len) {
71 close(fp);
72 unlink(*file);
73 g_critical("Could not write temp file %s", *file);
74 g_free(*file);
75
76 return FALSE;
77 }
78 close(fp);
79
80 return TRUE;
81 }
82
83 /**
84 * Returns a new allocates string for given value reference.
85 * String must be freed if not used anymore.
86 */
ext_util_js_ref_to_string(JSContextRef ctx,JSValueRef ref)87 char* ext_util_js_ref_to_string(JSContextRef ctx, JSValueRef ref)
88 {
89 char *string;
90 size_t len;
91 JSStringRef str_ref;
92
93 g_return_val_if_fail(ref != NULL, NULL);
94
95 str_ref = JSValueToStringCopy(ctx, ref, NULL);
96 len = JSStringGetMaximumUTF8CStringSize(str_ref);
97
98 string = g_new0(char, len);
99 JSStringGetUTF8CString(str_ref, string, len);
100 JSStringRelease(str_ref);
101
102 return string;
103 }
104