File: engine.cpp

package info (click to toggle)
k3d 0.8.0.2-6
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 40,692 kB
  • ctags: 39,695
  • sloc: cpp: 171,303; ansic: 24,129; xml: 6,995; python: 5,796; makefile: 726; sh: 22
file content (232 lines) | stat: -rw-r--r-- 6,618 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// K-3D
// Copyright (c) 1995-2009, Timothy M. Shead
//
// Contact: tshead@k-3d.com
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

/** \file
	\brief Implements Python engine, an implementation of k3d::iscript_engine that supports the Python language
	\author Anders Dahnielson (anders@dahnielson.com)
	\author Romain Behar (romainbehar@yahoo.com)
	\author Adam Hupp (hupp@cs.wisc.edu)
	\author Timothy M. Shead (tshead@k-3d.com)
*/

#include <k3d-i18n-config.h>
#include <k3dsdk/application_plugin_factory.h>
#include <k3dsdk/classes.h>
#include <k3dsdk/command_node.h>
#include <k3dsdk/file_helpers.h>
#include <k3dsdk/fstream.h>
#include <k3dsdk/iscript_engine.h>
#include <k3dsdk/module.h>
#include <k3dsdk/python/file_signal_python.h>
#include <k3dsdk/python/object_model_python.h>
#include <k3dsdk/result.h>
#include <k3dsdk/string_modifiers.h>

#include <boost/assign/list_of.hpp>
#include <boost/python.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/algorithm/string.hpp>

namespace module
{

namespace python
{

/// Magic token used to identify Python scripts
const k3d::string_t magic_token("#python");

/// Ensures that Py_Initialize() is called before any other Python API functions
class initialize_python
{
public:
	initialize_python()
	{
		if(!Py_IsInitialized())
		{
			Py_Initialize();

			try
			{
				initk3d();
			}
			catch(std::exception& e)
			{
				k3d::log() << error << e.what() << std::endl;
			}
			catch(...)
			{
				k3d::log() << error << "Unknown exception" << std::endl;
			}
		}
	}
};

class engine :
	public k3d::iscript_engine
{
public:
	k3d::iplugin_factory& factory()
	{
		return get_factory();
	}

	static k3d::iplugin_factory& get_factory()
	{
		static k3d::application_plugin_factory<engine, k3d::interface_list<k3d::iscript_engine> > factory(
			k3d::classes::PythonEngine(),
			"Python",
			_("Python scripting engine"),
			"ScriptEngine",
			k3d::iplugin_factory::STABLE,
			boost::assign::map_list_of("k3d:mime-types", "text/x-python"));

		return factory;
	}

	const k3d::string_t language()
	{
		return "Python";
	}

	k3d::bool_t execute(const k3d::string_t& ScriptName, const k3d::string_t& Script, context& Context, output_t* Stdout, output_t* Stderr)
	{
		k3d::bool_t succeeded = true;

		try
		{
			boost::scoped_ptr<k3d::python::file_signal> stdout_signal;
			boost::scoped_ptr<k3d::python::file_signal> stderr_signal;

			if(Stdout)
			{
				stdout_signal.reset(new k3d::python::file_signal());
				stdout_signal->connect_output_signal(*Stdout);
				PySys_SetObject(const_cast<char*>("stdout"), boost::python::object(*stdout_signal).ptr());
			}

			if(Stderr)
			{
				stderr_signal.reset(new k3d::python::file_signal());
				stderr_signal->connect_output_signal(*Stderr);
				PySys_SetObject(const_cast<char*>("stderr"), boost::python::object(*stderr_signal).ptr());
			}

			m_local_dict["context"] = Context;

			// The embedded python interpreter cannot handle DOS line-endings, see http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
			k3d::string_t script = Script;
			script.erase(std::remove(script.begin(), script.end(), '\r'), script.end());

			PyDict_Update(m_local_dict.ptr(), PyObject_GetAttrString(PyImport_AddModule("__main__"), "__dict__"));
			
			PyObject* const result = PyRun_String(const_cast<char*>(script.c_str()), Py_file_input, m_local_dict.ptr(), m_local_dict.ptr());
			if(result)
			{
				Py_DECREF(result);
				if(Py_FlushLine())
					PyErr_Clear();
			}
			else
			{
				PyErr_Print();
			}

			Context = boost::python::extract<k3d::iscript_engine::context>(m_local_dict["context"])();

			succeeded = result ? true : false;
		}
		catch(std::exception& e)
		{
			k3d::log() << error << k3d_file_reference << ": " << e.what() << std::endl;
			succeeded = false;
		}
		catch(...)
		{
			k3d::log() << error << k3d_file_reference << ": " << "Unknown exception" << std::endl;
			succeeded = false;
		}

		if(Stdout)
		      PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));

		if(Stderr)
		      PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));

		return succeeded;
	}

	k3d::bool_t halt()
	{
		return false;
	}

	const completions_t complete(const k3d::string_t& Command)
	{
		completions_t tokens_equal_token;
		boost::split(tokens_equal_token, Command, boost::is_any_of("= "));
		completions_t tokens, completions;
		boost::split(tokens, tokens_equal_token.back(), boost::is_any_of("."));
		if(tokens.size() == 1)
		{
			const boost::python::list locals_keys = m_local_dict.keys();
			append_completions(locals_keys, tokens[0], completions);
		}
		else if(tokens.size() > 1)
		{
			if(!m_local_dict.has_key(tokens[0]))
				return completions;
			boost::python::object obj = m_local_dict[tokens[0]];
			for(k3d::uint_t i = 1; i != (tokens.size() - 1); ++i)
			{
				obj = boost::python::getattr(obj, tokens[i].c_str());
				if(!obj.ptr())
					return completions;
			}
			PyObject* dir = PyObject_Dir(obj.ptr());
			return_val_if_fail(PyList_Check(dir), completions);
			const boost::python::list candidates = boost::python::extract<boost::python::list>(dir);
			append_completions(candidates, tokens[tokens.size() - 1], completions);
		}
		return completions;
	}

private:
	void append_completions(const boost::python::list& Candidates, const k3d::string_t& ToComplete, completions_t& Completions)
	{
		for(k3d::uint_t i = 0; i != boost::python::len(Candidates); ++i)
		{
			const k3d::string_t completion_candidate = boost::python::extract<k3d::string_t>(Candidates[i]);
			if(boost::algorithm::starts_with(completion_candidate, ToComplete))
				Completions.push_back(completion_candidate);
		}
	}

	initialize_python m_initialize_python;
	boost::python::dict m_local_dict;
};

} // namespace python

} // namespace module

K3D_MODULE_START(Registry)
	Registry.register_factory(module::python::engine::get_factory());
K3D_MODULE_END