1 /*
2  * This source file is part of libRocket, the HTML/CSS Interface Middleware
3  *
4  * For the latest information, see http://www.librocket.com
5  *
6  * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  *
26  */
27 
28 #include "precompiled.h"
29 #include "ElementDocumentWrapper.h"
30 #include "../../../Include/Rocket/Core/Stream.h"
31 #include "../../../Include/Rocket/Core/Python/Utilities.h"
32 
33 namespace Rocket {
34 namespace Core {
35 namespace Python {
36 
ElementDocumentWrapper(PyObject * self,const char * tag)37 ElementDocumentWrapper::ElementDocumentWrapper(PyObject* self, const char* tag) : ElementWrapper< ElementDocument >(self, tag)
38 {
39 	Rocket::Core::String module_id(32, "document_%x", this);
40 
41 	// Create a new module
42 	module = PyModule_New(module_id.CString());
43 	module_namespace = PyModule_GetDict(module);
44 
45 	// Merging main into the module
46 	PyObject* builtins = PyImport_AddModule("__main__");
47 	PyObject* builtins_dict = PyModule_GetDict( builtins);
48 	PyDict_Merge(module_namespace, builtins_dict, 0);
49 
50 	// Insert the document global
51 	PyDict_SetItemString(module_namespace, "document", self);
52 }
53 
~ElementDocumentWrapper()54 ElementDocumentWrapper::~ElementDocumentWrapper()
55 {
56 	// Release the module
57 	Py_DECREF(module);
58 }
59 
LoadScript(Rocket::Core::Stream * stream,const Rocket::Core::String & source_name)60 void ElementDocumentWrapper::LoadScript(Rocket::Core::Stream* stream, const Rocket::Core::String& source_name)
61 {
62 	// If theres a source, check if the code is already loaded and just reuse it
63 	if (!source_name.Empty())
64 	{
65 		Rocket::Core::String module_name = Rocket::Core::String(source_name).Replace("/", "_");
66 		module_name = module_name.Replace("\\", "_");
67 		module_name = module_name.Replace(".py", "");
68 
69 		PyObject* modules = PyImport_GetModuleDict();
70 		PyObject* merge_module = PyDict_GetItemString(modules, module_name.CString());
71 
72 #ifdef ROCKET_DEBUG
73 		// In debug builds, force module to NULL so that scripts are always reloaded
74 		merge_module = NULL;
75 #else
76 		if (merge_module)
77 		{
78 			Py_INCREF(merge_module);
79 		}
80 #endif
81 
82 		if (!merge_module)
83 		{
84 			// Compile the code as a python module
85 			Rocket::Core::String source_buffer;
86 			PreprocessCode(source_buffer, stream);
87 
88 			PyObject* code = Py_CompileString(source_buffer.CString(), source_name.CString(), Py_file_input);
89 			if (code)
90 			{
91 				merge_module = PyImport_ExecCodeModule((char*)module_name.CString(), code);
92 				Py_DECREF(code);
93 			}
94 		}
95 
96 		if (merge_module)
97 		{
98 			PyObject* dict = PyModule_GetDict(merge_module);
99 			PyDict_Merge(module_namespace, dict, 0);
100 			Py_DECREF(merge_module);
101 		}
102 		else
103 		{
104 			Rocket::Core::Python::Utilities::PrintError();
105 		}
106 	}
107 	else
108 	{
109 		// Compile directly onto the python module
110 		Rocket::Core::String source_buffer;
111 		PreprocessCode(source_buffer, stream);
112 
113 		PyObject* result = PyRun_String(source_buffer.CString(), Py_file_input, module_namespace, module_namespace);
114 		if ( !result )
115 		{
116 			Rocket::Core::Python::Utilities::PrintError();
117 		}
118 		else
119 		{
120 			Py_DECREF(result);
121 		}
122 	}
123 }
124 
GetModuleNamespace()125 PyObject* ElementDocumentWrapper::GetModuleNamespace()
126 {
127 	return module_namespace;
128 }
129 
PreprocessCode(Rocket::Core::String & code,Rocket::Core::Stream * stream)130 void ElementDocumentWrapper::PreprocessCode(Rocket::Core::String &code, Rocket::Core::Stream *stream)
131 {
132 	// Load in the script
133 	Rocket::Core::String buffer;
134 	stream->Read(buffer, stream->Length());
135 
136 	// Strip comments and build up code
137 	code = "";
138 
139 	size_t i = 0;
140 	size_t line_start = 0;
141 	enum ParseState { START, COMMENT, DATA };
142 	ParseState state = START;
143 
144 	while (i < buffer.Length())
145 	{
146 		// Python doesn't like \r's, strip them
147 		if (buffer[i] == '\r')
148 		{
149 			buffer.Erase(i, 1);
150 
151 			// Make sure we get out if there are no characters left
152 			if (i == buffer.Length())
153 				continue;
154 		}
155 
156 		switch (state)
157 		{
158 			case START:
159 			{
160 				// Check for the start of comments or non whitespace data
161 				if (buffer[i] == '#')
162 					state = COMMENT;
163 				else if (!Rocket::Core::StringUtilities::IsWhitespace(buffer[i]))
164 					state = DATA;
165 			}
166 			break;
167 
168 			default:
169 			{
170 				// If we've hit the end of the line, process as required
171 				if (buffer[i] == '\n')
172 				{
173 					if (state == DATA)
174 						code += buffer.Substring(line_start, i - line_start + 1);
175 
176 					state = START;
177 					line_start = i + 1;
178 				}
179 			}
180 			break;
181 		}
182 
183 		i++;
184 	}
185 }
186 
187 }
188 }
189 }
190