aboutsummaryrefslogtreecommitdiff
path: root/externals/grill/py/source/py.cpp
blob: 05aeea8d950e1ab0df0cf5a5151d1182dedd7030 (plain)
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* 

py/pyext - python script object for PD and Max/MSP

Copyright (c)2002-2005 Thomas Grill (gr@grrrr.org)
For information on usage and redistribution, and for a DISCLAIMER OF ALL
WARRANTIES, see the file, "license.txt," in this distribution.  

*/

#include "main.h"


class pyobj:
	public py
{
	FLEXT_HEADER_S(pyobj,py,Setup)

public:
	pyobj(int argc,const t_atom *argv);
	~pyobj();

protected:
	bool m_method_(int n,const t_symbol *s,int argc,const t_atom *argv);

	bool work(const t_symbol *s,int argc,const t_atom *argv); 

	void m_bang() { callwork(sym_bang,0,NULL); }
	void m_reload();
	void m_reload_(int argc,const t_atom *argv);
	void m_set(int argc,const t_atom *argv);
    void m_dir_() { m__dir(function); }
    void m_doc_() { m__doc(function); }

	virtual void m_help();

	// methods for python arguments
	void callwork(const t_symbol *s,int argc,const t_atom *argv);
	
	void m_py_list(int argc,const t_atom *argv) { callwork(sym_list,argc,argv); }
	void m_py_float(int argc,const t_atom *argv) { callwork(sym_float,argc,argv); }
	void m_py_int(int argc,const t_atom *argv) { callwork(sym_int,argc,argv); }
	void m_py_any(const t_symbol *s,int argc,const t_atom *argv) { callwork(s,argc,argv); }

	const t_symbol *funname;
	PyObject *function;

	virtual void Reload();

	void SetFunction(const char *func);
	void ResetFunction();

private:

    virtual bool callpy(PyObject *fun,PyObject *args);

	static void Setup(t_classid c);

	FLEXT_CALLBACK(m_bang)
	FLEXT_CALLBACK(m_reload)
	FLEXT_CALLBACK_V(m_reload_)
	FLEXT_CALLBACK_V(m_set)
	FLEXT_CALLBACK(m_dir_)
	FLEXT_CALLBACK(m_doc_)

	FLEXT_CALLBACK_V(m_py_float)
	FLEXT_CALLBACK_V(m_py_list)
	FLEXT_CALLBACK_V(m_py_int)
	FLEXT_CALLBACK_A(m_py_any)

#ifdef FLEXT_THREADS
	FLEXT_THREAD_A(work)
#else
	FLEXT_CALLBACK_A(work)
#endif
};

FLEXT_LIB_V("py",pyobj)


void pyobj::Setup(t_classid c)
{
	FLEXT_CADDBANG(c,0,m_bang);
	FLEXT_CADDMETHOD_(c,0,"reload",m_reload_);
	FLEXT_CADDMETHOD_(c,0,"reload.",m_reload);
	FLEXT_CADDMETHOD_(c,0,"set",m_set);
	FLEXT_CADDMETHOD_(c,0,"doc",m_doc);
	FLEXT_CADDMETHOD_(c,0,"doc+",m_doc_);
#ifdef FLEXT_THREADS
	FLEXT_CADDATTR_VAR1(c,"detach",detach);
	FLEXT_CADDMETHOD_(c,0,"stop",m_stop);
#endif
	FLEXT_CADDMETHOD_(c,0,"dir",m_dir);
	FLEXT_CADDMETHOD_(c,0,"dir+",m_dir_);

	FLEXT_CADDMETHOD_(c,1,"float",m_py_float);
	FLEXT_CADDMETHOD_(c,1,"int",m_py_int);
	FLEXT_CADDMETHOD(c,1,m_py_list);
	FLEXT_CADDMETHOD(c,1,m_py_any);

  	FLEXT_CADDATTR_VAR1(c,"respond",respond);
}

pyobj::pyobj(int argc,const t_atom *argv):
	function(NULL),funname(NULL)
{ 
	PyThreadState *state = PyLock();

	AddInAnything(2);  
	AddOutAnything();  

	if(argc > 2) 
		SetArgs(argc-2,argv+2);
	else
		SetArgs(0,NULL);

	// init script module
	if(argc >= 1) {
		if(!IsString(argv[0])) 
			post("%s - script name argument is invalid",thisName());
        else {
		    char dir[1024];
		    GetModulePath(GetString(argv[0]),dir,sizeof(dir));
		    // set script path
		    AddToPath(dir);

#if FLEXT_SYS == FLEXT_SYS_PD
			// add dir of current patch to path
			AddToPath(GetString(canvas_getdir(thisCanvas())));
			// add current dir to path
			AddToPath(GetString(canvas_getcurrentdir()));
#elif FLEXT_SYS == FLEXT_SYS_MAX 
/*
			short path = patcher_myvol(thisCanvas());
			path_topathname(path,NULL,dir); 
			AddToPath(dir);       
*/
#else 
	        #pragma message("Adding current dir to path is not implemented")
#endif

			ImportModule(GetString(argv[0]));
        }
	}

	Register("_py");

	if(argc >= 2) {
		// set function name
		if(!IsString(argv[1])) 
			post("%s - function name argument is invalid",thisName());
		else {
			// Set function
			SetFunction(GetString(argv[1]));
		}
	}

	PyUnlock(state);
}

pyobj::~pyobj() 
{
	PyThreadState *state = PyLock();
	Unregister("_py");
	PyUnlock(state);
}




bool pyobj::m_method_(int n,const t_symbol *s,int argc,const t_atom *argv)
{
	if(n == 1)
		post("%s - no method for type %s",thisName(),GetString(s));
	return false;
}

void pyobj::m_reload()
{
	PyThreadState *state = PyLock();

	Unregister("_py");

	ReloadModule();
	Reregister("_py");
	Register("_py");
	SetFunction(funname?GetString(funname):NULL);

	PyUnlock(state);
}

void pyobj::m_reload_(int argc,const t_atom *argv)
{
	PyThreadState *state = PyLock();
	SetArgs(argc,argv);
	PyUnlock(state);

	m_reload();
}

void pyobj::m_set(int argc,const t_atom *argv)
{
	PyThreadState *state = PyLock();

	int ix = 0;
	if(argc >= 2) {
		if(!IsString(argv[ix])) {
			post("%s - script name is not valid",thisName());
			return;
		}
		const char *sn = GetString(argv[ix]);

		if(!module || !strcmp(sn,PyModule_GetName(module))) {
			ImportModule(sn);
			Register("_py");
		}

		++ix;
	}

	if(!IsString(argv[ix])) 
		post("%s - function name is not valid",thisName());
	else
		SetFunction(GetString(argv[ix]));

	PyUnlock(state);
}

void pyobj::m_help()
{
	post("");
	post("%s %s - python script object, (C)2002-2005 Thomas Grill",thisName(),PY__VERSION);
#ifdef FLEXT_DEBUG
	post("DEBUG VERSION, compiled on " __DATE__ " " __TIME__);
#endif

	post("Arguments: %s [script name] [function name] {args...}",thisName());

	post("Inlet 1:messages to control the py object");
	post("      2:call python function with message as argument(s)");
	post("Outlet: 1:return values from python function");	
	post("Methods:");
	post("\thelp: shows this help");
	post("\tbang: call script without arguments");
	post("\tset [script name] [function name]: set (script and) function name");
	post("\treload {args...}: reload python script");
	post("\treload. : reload with former arguments");
	post("\tdoc: display module doc string");
	post("\tdoc+: display function doc string");
	post("\tdir: dump module dictionary");
	post("\tdir+: dump function dictionary");
#ifdef FLEXT_THREADS
	post("\tdetach 0/1/2: detach threads");
	post("\tstop {wait time (ms)}: stop threads");
#endif
	post("");
}

void pyobj::ResetFunction()
{
	if(!module || !dict) 
	{ 
		post("%s - No module loaded",thisName());
		function = NULL; 
		return; 
	}

	function = funname?PyDict_GetItemString(dict,(char *)GetString(funname)):NULL; // borrowed!!!
	if(!function) {
		PyErr_Clear();
		if(funname) post("%s - Function %s could not be found",thisName(),GetString(funname));
	}
	else if(!PyFunction_Check(function)) {
		post("%s - Object %s is not a function",thisName(),GetString(funname));
		function = NULL;
	}
}

void pyobj::SetFunction(const char *func)
{
	if(func) {
		funname = MakeSymbol(func);
		ResetFunction();
	}
	else 
		function = NULL,funname = NULL;
}


void pyobj::Reload()
{
	ResetFunction();
}

bool pyobj::callpy(PyObject *fun,PyObject *args)
{
    PyObject *ret = PyObject_Call(fun,args,NULL); 
    if(ret == NULL) {
        // function not found resp. arguments not matching
        PyErr_Print();
        return false;
    }
    else {
        AtomList *rargs = GetPyArgs(ret);
		if(!rargs) 
            PyErr_Print();
        else {
            // call to outlet _outside_ the Mutex lock!
            // otherwise (if not detached) deadlock will occur
            if(rargs->Count()) ToOutList(0,*rargs);
            delete rargs;
        }
        Py_DECREF(ret);
        return true;
    }
} 

void pyobj::callwork(const t_symbol *s,int argc,const t_atom *argv)
{
    bool ret = false;
 
	if(function) {
        PyThreadState *state = PyLock();
    
		PyObject *pargs = MakePyArgs(s,argc,argv);
        Py_INCREF(function);
        ret = gencall(function,pargs);

        PyUnlock(state);
    }
	else {
		post("%s: no function defined",thisName());
        ret = false;
	}

    Respond(ret);
}